• 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对象;
  • 相关阅读:
    清北学堂2019.7.18 & 清北学堂2019.7.19
    清北学堂2019.7.17
    清北学堂2019.7.16
    清北学堂2019.7.15
    清北学堂2019.7.14
    清北学堂2019.7.13
    【洛谷P1383 高级打字机】
    考试整理
    考试整理
    【洛谷P5018 对称二叉树】
  • 原文地址:https://www.cnblogs.com/lhl66/p/7968175.html
Copyright © 2020-2023  润新知