匿名函数里的this的执行环境和指向--javascript

重新看了下闭包,在javascript高级程序设计第二版里的闭包里有如下例子,例子中介绍说匿名函数的执行环境具有全局性和this指向window,对于这句话很费解,所以就想个方法验证下。文章来源地址https://www.yii666.com/article/764193.html

var name = "The Window";
      var object = {
        name : "My Object",
        getNameFunc : function(){
          return function(){
            return this.name;
          };
        }
      };
      alert(object.getNameFunc()());输出 The Window

一.匿名函数的执行环境具有全局性,因此其this对象通常指向window,也可以称的上是window对象的方法的验证

var a = 100;
      (function  () {
          console.log(a);
          console.log(this.a);
          console.log(window.a);
      })()
输出
100
100
100
(function  () {
          this.a = 200;
      })();

       console.log(window.a);
       console.log(this.a);
       console.log(a);

输出
200
200
200

上面两个例子验证了匿名函数的上下文环境是window文章来源地址:https://www.yii666.com/article/764193.html

二.将闭包的题改一下来验证匿名函数的this

var object = {
        name : "My Object",
        getNameFunc : function(){
          return function(){
                   if (this===window)
                       {return "匿名函数的上下文环境是window";}
                   else
                       {return "匿名函数的上下文环境不是window";};
           
          };
        }
      };
      alert(object.getNameFunc()());

//输出  匿名函数的上下文环境是window

三.下面是从网上看的一篇文章上的代码

function foo() {

    if (this===window) {
        document.write("call a function");
    }
    else{
        document.write("call a function or method");
    }
    }

    function MyObject(name) {
        // 下面的this指代new关键字新创建实例
        this.name = name;
        this.foo = function(){
            document.write("call a method, by object: ", this.name, " ; and then ");
            foo();
        };
    }

    var obj1 = new MyObject("obj1");
    var obj2 = new MyObject("obj2");

    // 测试1: 作为函数调用
    foo();        //Output=>call a function.

    // 测试2: 作为对象方法的调用
    obj1.foo();    //Output=>call a method, by object: obj1 ; and then call a function.
    obj2.foo();    //Output=>call a method, by object: obj2 ; and then call a function.

    // 测试3: 将函数作为“指定对象的”方法调用
    foo.call(obj1);    //Output=>call a function or method.
    foo.apply(obj2);    //Output=>call a function or method.

全局foo()函数也是方法,它其实是其上下文环境(window)的方法网址:yii666.com<

参考:文章地址https://www.yii666.com/article/764193.html

http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html网址:yii666.com

http://www.ibm.com/developerworks/cn/web/1207_wangqf_jsthis/

版权声明:本文内容来源于网络,版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。文本页已经标记具体来源原文地址,请点击原文查看来源网址,站内文章以及资源内容站长不承诺其正确性,如侵犯了您的权益,请联系站长如有侵权请联系站长,将立刻删除

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信图片_20190322181744_03.jpg

微信扫一扫打赏

请作者喝杯咖啡吧~

支付宝扫一扫领取红包,优惠每天领

二维码1

zhifubaohongbao.png

二维码2

zhifubaohongbao2.png