this is sparta
大多數情況下,this 是由「在哪裡呼叫」決定的。大多數情況下 this 是全域物件(在瀏覽器就是 Window,因為大多數時候,最開始的呼叫就是從 Window 開始 ),除非:
- 由
bindorapply綁定指定參數,那this就是被指定的參數。 - 由
new產生新物件,那this就是該新物件。 - 該函式在某個物件內,那
this就是該物件。
另外,在嚴謹模式(strict mode)下,「在哪裡呼叫」的規則會嚴格執行:很多只有呼叫函式的寫法,其實是省略了 Window 這個(全域變數)主詞。也就是說,foo() 呼叫,其實該寫成 Window.foo()。如果沒有這主詞,你就會看到一個 undefined。
對了,在嚴謹模式,你可能想這麼玩:
function foo()
{
"use strict";
this.foo = "Bar";
return this;
}
console.log( undefined.foo() ); // TypeError: undefined has no properties
undefined: 但我拒絕,我 undefined 最喜歡做的一件事,就是對自以為能玩壞我的傢伙說「不」!
var all_prop = function(ap){ return ap.prop; };
var another_prop = function(){ return this.prop; };
var test = {
//"use strict";
prop: 42,
func: function() {
return this.prop;
},
f:all_prop(this),
fu:another_prop()
};
console.log(test.fu());
console.log(test.f());
// expected output: 42
// But actually is: "Error: test.fu is not a function"
問題:為什麼不能呼叫 test.fu() 或是呼叫 test.f()?