3
function katana(){
  this.isSharp = true;
}
katana();
assert( isSharp === true, "A global object now exists with that name and value." );

var shuriken = {
  toss: function(){
    this.isSharp = true;
  }
};
shuriken.toss();
assert( shuriken.isSharp === true, "When it's an object property, the value is set within the object." );

我实际上没有得到这段代码试图告诉什么?谁能解释一下 JavaScript 中的 Context 是什么,以及上面代码中的 context 到底代表什么?

4

2 回答 2

3

好吧,this === window第一个示例和this === shuriken第二个示例中的原因都与创建这些函数的位置有关。请注意,当您shuirken.toss在对象之外定义时,this指向窗口对象。当你调用katanawith时newthis指向新创建的对象。

于 2012-12-27T01:34:20.020 回答
3

第一次调用相当于:

katana.call(window); // window is now referenced as this inside the function

以类似的方式,您可以将调用更改为katana()这样以更改上下文:

var shuriken = {}
katana.call(shuriken); // shuriken.isSharp === true

第二次调用隐含了这个等效的函数调用:

shuriken.toss.call(shuriken);
于 2012-12-27T01:39:13.333 回答