this的值

  • 在面向对象的编程中,this值很重要,且它的值取决于调用的模式
  1. 方法调用模式:this被绑定到该对象
    1   var name = "outer";
    2   var myObj = {
    3       name : "inner",
    4       getName : function () {
    5           return this.name;
    6       }
    7   };
    8   console.log(myObj.getName());   //inner,this指向myObj
  2. 函数调用模式:this被绑定到全局对象
     1   var name = "outer";
     2   var myObj = {
     3       name : "inner",
     4       getName : function () {
     5           return function(){
     6               return this.name;
     7           };
     8       }
     9   };
    10   console.log(myObj.getName()());  //outer,this指向window

    解决办法为

     1 var name = "outer";
     2   var myObj = {
     3       name : "inner",
     4       getName : function () {
     5           var that = this;
     6           return function(){
     7               return that.name;
     8           };
     9       }
    10   };
    11   console.log(myObj.getName()());  //inner
  3. 构造器调用模式:在函数前面使用new来调用,会创建连接到该函数的prototype属性的新对象,this会绑定到这个新对象上
    1   function Dog (color) {
    2       this.color = color;
    3   }
    4   Dog.prototype.getColor = function (){
    5       return this.color;
    6   };
    7   var dog = new Dog("yellow");  //this绑定到dog上
    8   console.log(dog.getColor());  //yellow
  4. Apply/Call调用模式:函数拥有这两个方法,允许我们选择this的值
     1   var name = "outer";
     2      var myObj = {
     3        name : "inner",
     4        getName : function () {
     5            return this.name;
     6        }
     7    };
     8    
     9    console.log(myObj.getName());   //inner,this指向myObj
    10    console.log(myObj.getName.apply(window));   //outer,this指向window

    总结:在调用函数时,对参数this及arguments的搜索不遵守作用域链规则

原文地址:https://www.cnblogs.com/webliu/p/4715423.html