zoukankan      html  css  js  c++  java
  • 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  
  • 相关阅读:
    oo第八次作业--5,6,7次作业总结
    OO前三次作业总结
    软工总结
    黄衫感想博客
    软工结对编程博客
    软工第一次阅读
    软工第0次作业
    OO第四次博客
    OO第三次博客
    OO第二次博客
  • 原文地址:https://www.cnblogs.com/lulin1/p/7324435.html
Copyright © 2011-2022 走看看