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  
  • 相关阅读:
    HDU5873
    HDU5874
    HDU1565(状态压缩dp)
    POJ2774(二分+哈希)
    HDU4474
    HDU2602(背包)
    单链表
    POJ2503(hash)
    POJ1200(hash)
    顺序表
  • 原文地址:https://www.cnblogs.com/lulin1/p/7324435.html
Copyright © 2011-2022 走看看