js- this

  this对象是基于函数在执行的环境绑定的。

(一)

     this 在闭包环境中指向的对象。

   《Js高级程序设计》中提到:

     每个函数在被调用时,其活动对象都会自动取得两个特殊变量:this和arguments。

     内部函数搜索这两个this,arguments时,只会搜索到其活动对象为止,因此永远不可能直接访问外部函数中的变量。 

      这一点我个人有些不解.

   1、匿名函数中 this一般指向window对象。

   2、闭包函数中的this,指向window。

 1     var dogName="window dog";
 2         var dog={
 3             dogName:"little dog",
 4             dogAge:19,
 5             getName:function getName(){
 6                 console.log(this.dogName);
 7                 console.log("------------------------");
 8                 var testName=123;
 9                 return function(){
10                     console.log(testName);
11                     console.log(dogAge);
12                     console.log( this.dogName);
13                 }
14             }
15         };
16         dog.getName()();

   在 11行中,是访问不到dogAge变量的。

   从第5行到第14行,是一个闭包。 dogAge属性是不属于这个闭包内容的,因此不能访问。

     闭包中的匿名函数,this指向的是window。

(二)

  一般情况下,this指向函数的拥有者。

  但在自执行函数中,this指向window对象。

 1         var age=18;
 2         var xiaoMing={
 3             age:19,
 4             showAge:function(){
 5                 this.age=20;
 6                 (function(){
 7                     console.log(this.age);
 8                 })();
 9                 console.log(this.age);
10             }
11         };
12 
13         xiaoMing.showAge();

    输出结果  18, 20

(三)

   setTimeout,setInterval与this。

      function Dog(msg) {
            this.msg = msg;
            this.shout = function () {
                console.log(this.msg);
            };
            this.waitAndShout=function(){
                setTimeout(this.shout,2000);
            };
        }
        var exp=new Dog('abc');
        exp.waitAndShout(); 

  输出结果 undefined.

  这是因为 Window.prototype.setTimeout = function(code,delay) {}; 

  因此,这里的 this指向的是 Window对象。

  如何破?

  (1)

    使用ES5新增的  Function.prototype.bind = function(thisArg,arg) {}; 

    绑定 当前我们指向的 this对象,为当前函数。

    setTimeout(this.shout.bind(this),2000);

   (2)

    使用闭包得到当前作用域。

    自执行函数传入当前对象和方法,返回闭包,通过call()或apply()改变函数执行环境,使this指向其对象。

           this.waitAndShout=function(){
                setTimeout(function(a,b){
                  return function(){
                      b.call(a);
                  };
                }(this,this.shout),2000);
            };    

      (3)

    保存当前对象this为别名 that, 暂存this对象,不去混淆。

             this.waitAndShout=function(){
                var that=this;
                setTimeout(function(){
                    that.shout();
                },2000);  
              }

 (四)

   this  遇到 return 如何办?

   如果return的是一个对象A,则指向对象A;

   如果return的是不是对象,则仍然指向这个函数的实例。

  

原文地址:https://www.cnblogs.com/xianrongbin/p/5230933.html