方法内的函数 ---之js this绑定的不合理

    xiaoxiao2022-06-24  30

      当一个函数并非一个对象的方法时,那么他被当做一个函数来调用。

     当函数以此模式调用时,this被绑定到全局对象。这是语言设计上的一个错误。倘若语言设计正确,当内部函数被调用时,this应该仍然绑定到外部函数的this变量。这个设计错误的后果是方法不能利用内部函数来帮助他工作,因为内部函数的this被绑定了错误的值,所以不能共享该方法对对象的访问权。幸运的是,有一个很容易的解决方案:如果该犯法定义一个变量并发给他赋值this,那么内部函数就可以听过那个变量访问到this。如下,

       //给myObject 增加一个double方法。

     myObject.double b=function(){

         var that =this ;

         var helper =function(){

           that.value =add(that.value,that.value);

         };

         helper();  //以函数的形式调用helper。

      };

    //以方法的形式调用double

    myObject.double();

    document.writeln(myObject.getValue);

    另一个demo

    <!DOCTYPE html> <html> <head> <title>方法内函数</title> </head> <body> <script type="text/javascript"> var myObject ={ a:1, b:2 }; myObject.my =function(){ console.log('my this' +this); //var that =this;         var add =function(){            console.log('add this' +this);            console.log(this.a + this.b);         }         //add(myObject.a,myObject.b);         add(); } myObject.my(); </script> </body> </html>

    转载请注明原文地址: https://ju.6miu.com/read-1123871.html

    最新回复(0)