2014-01-08 30 views
1

誰能告訴我如何isSharp是在global context下面的代碼。我正在關注約翰先進的JS。上下文代表什麼?

http://ejohn.org/apps/learn/#24

function katana(){ 
    this.isSharp = true; 
} 
katana(); 
alert(isSharp); 
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."); 
+2

也許您應該在MDN上閱讀[this'關鍵字的介紹](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) – Bergi

回答

3

在未在對象上執行的代碼 - this指全局上下文。

這是this如何在一種語言中工作的一部分。

注 - 如果您使用嚴格模式,您應該 - 這將引發TypeError。


參考:"entering function code"

否則如果thisArg是null或undefined,則ThisBinding設置爲全局對象。