zoukankan      html  css  js  c++  java
  • this常用的用法

    1.函数作为对象的方法时,this指的是该对象;
    var obj ={
     name:"bob",
     age:25,
     getName:function(){
       console.log(this.name)  ------->//bob
     }
    }
    obj.getName();
    
    2.局部函数里的this指的是window对象
    var age=30;
    var obj ={
     name:"bob",
     age:25,
     getAge:function(){
       function aa(){
        console.log(this.age) ------->//30
       }
       aa();
       console.log(this.age)  ------->//25
     }
    }
    obj.getAge();
    
    3.构造函数动态this
    function Car(name,price){  //构造函数
      this.name = name;
      this.age = age;
      this.date = "2016.03.02";
    }
    
    Car.prototype.start = function(){
      console.log(this.name + "定义函数对象的方法一")
    }
    
    Car.prototype.end = function(){
      console.log(this.name + "定义函数对象的方法二")
    }
    
    Car.prototype.getPrice = function(){
      console.log(this.price + "定义函数对象的方法三") //this指动态绑定对象 的实例(obj1,obj2谁做的)
    }
    
    var obj1 = new Car("宝马",1000000)  -------->创建一个新的对象
    var obj2 = newCar("奥迪",400000)    -------->再创建一个对象分配另一个实例 
    obj1.getPrice();    -------->//它调用时候是1000000
    obj2.getPrice();    -------->//它调用时候是400000
    
    4.this的链式调用
    function Car(name,price){  //构造函数
      this.name = name;
      this.age = age;
      this.date = "2016.03.02";
    }
    
    Car.prototype.start = function(){
      console.log(this.name + "定义函数对象的方法一")
      return this;
    }
    
    Car.prototype.end = function(){
      console.log(this.name + "定义函数对象的方法二")
      return this;
    }
    
    Car.prototype.getPrice = function(){
      console.log(this.price + "定义函数对象的方法三") //this指动态绑定对象 的实例(obj1,obj2谁做的)
      return this;
    }
    
    var obj1 = new Car("宝马",1000000)  -------->创建一个新的对象
    var obj2 = newCar("奥迪",400000)    -------->再创建一个对象分配另一个实例 
    obj1.getPrice();    -------->//它调用时候是1000000
    obj2.getPrice();    -------->//它调用时候是400000
    
    obj1.getPrice().start().end(); -------->//它调用了三个方法,是通过retur this来实现!!!
    
    如果函数直接调用如 aa();默认this为window对象;
  • 相关阅读:
    vue : 无法加载文件 C:UsersxxxAppDataRoaming pmvue.ps1,因为在此系统上禁止运行脚本
    VSCode搭建简单的Vue前端项目
    Ant Design和Ant Design Pro
    React、Vue、AngularJS、Bootstrap、EasyUI 、AntDesign、Element理解
    CTF-flag在index里 80
    Web安全之XSS漏洞专题和Web安全之命令执行漏洞专题—第五天
    CTF-web4 80
    Sqli-labs-第五关详解
    Web安全之文件上传漏洞专题--第四天.
    Sqli_labs第1-4关&&sqlmap.py的初步使用
  • 原文地址:https://www.cnblogs.com/lhl66/p/7968175.html
Copyright © 2011-2022 走看看