this

在函数内部定义的函数,其this也会指向全局,而和我们希望的恰恰相反。代码如下:

var point = {   
 x : 0,   
 y : 0,   
 moveTo : function(x, y) { 
         // 内部函数  
         var moveX = function(x) {   
           this.x = x;//this 绑定到了全局  
         };   
         // 内部函数  
         var moveY = function(y) {   
          this.y = y;//this 绑定到了全局  
         };   
  
         moveX(x);   
         moveY(y);   
        }   
 };   
 point.moveTo(1, 1);   
 point.x; //==>0   
 point.y; //==>0   
 x; //==>1   
 y; //==>1  

我们会发现不但我们希望的移动呢效果没有完成,反而会多出两个全局变量。那么如何解决呢?只要要进入函数中的函数时将this保存到一个变量中,再运用该变量即可。代码如下:

var point = {   
 x : 0,   
 y : 0,   
 moveTo : function(x, y) {   
      var that = this;   
     // 内部函数  
     var moveX = function(x) {   
       that.x = x;   
     };   
     // 内部函数  
     var moveY = function(y) {   
       that.y = y;   
     }   
     moveX(x);   
     moveY(y);   
     }   
 };   
 point.moveTo(1, 1);   
 point.x; //==>1   
 point.y; //==>1  
原文地址:https://www.cnblogs.com/lulin1/p/7324435.html