2012-02-28 52 views
0

http://jsfiddle.net/raylu/C6Tkn/为什么在这个JS片段中上下文发生变化?

function a() { 
    document.write(this + '<br />'); 
} 

a(); 
a.apply('hello'); 

var b = function() { 
    a(); 
} 
b.apply('hi');​ 

我希望最后一行输出“HI”,而是它输出窗口。

+0

[MDN有一个关于'this'的好页面](https://developer.mozilla.org/en/JavaScript/Reference/Operators/this)。每当你调用像func();这样的函数时,this就会引用全局对象。 – 2012-02-28 04:44:07

+0

可能的重复[为什么'this'在函数参数作为字符串或引用传递时发生变化?](http://stackoverflow.com/questions/5883619/why-does-this-change-when-passing-the-function -argument-AS-字符串或引用) – PeeHaa 2012-02-29 17:16:32

回答

0

this在这种情况下应该是window

b()this'hi',但不被继承/相关的任何功能在b()函数体调用。这就是为什么this内部的a()当通过b()与正常的函数调用方法(())调用时是window

相关问题