When a function is invoked as a function rather that as a method, the this keyword refers to the global object. Confusingly, this is true even when a nested function is invoked (as a function) within a containing method that was invoked as a method: the this keyword has one value in the containing function but (counterintuitively) refers to the global object within the body of the nested function.
《权威指南》8.4节倒数第二段求教这一段话的意思?中文版的我没看懂。先谢谢大家了!

解决方案 »

  1.   

    那段话貌似说明函数的关键字“this”,这样理解也许更全面简单些:
    函数体内都存在一个关键字(类似指针)“this”,未运行“this”指向该函数的原型prototype,运行了则“this”指向(指代)调用该函数的对象。例如:
    1、function fun(){this.x=3};var f=new fun;alert(f.x);该函数未运行,this指向它的原型,通过new算符派生出来的实例“f”继承了原型“this”的属性“x”。2、function fun(){alert(this===widnow)};fun();该this就是window,因为window引用了该函数(fun()其实window.fun()就如setTimeout()其实window.setTimeout()一样),同理匿名函数的this也指向window。
    3、obj={fun:function(){alert(this===obj)}};obj.fun();该this就是obj,因为是obj引用了该函数。
      

  2.   

    当一个函数是作为函数被调用,而不是作为某个对象的方法,则this关键字指向的是全局对象。 这种情况下,即使是在被嵌套调用时,this指向的仍是全局对象,而不是调用它的函数。相反,如果一个函数是某个对象的方法,则this指向的是距离它最近的调用它的对象。
      

  3.   

    我对这段话的理解如下:
    function print() {
        for (var i = 0; i < arguments.length; ++i) {
          document.write(arguments[i], "&nbsp;&nbsp;&nbsp;&nbsp;");
        }
        document.write("<br/>");
    }function func() {
        print( "this of Func:", this, "this == window:", this == window );
        
        function nestedFunc() {
            print( "this of nestedFunc:", this, "this == window:", this == window );
        }
        
        nestedFunc();
    }print("<b>call by function:</b>");
    func();print();print("<b>call by method:</b>");
    func.call(new Object);