2012-06-10 37 views
4

我試圖做一個沒有原型的類。這裏是一個例子:`this`裏面的函數不是一個類的原型

test = (function() { 
    this.value = 1; 
    this.print = function() { 
    console.log(this.value); 
    }; 
    return this; 
})(); 

這個完美的按預期工作。我不明白的是this.value裏面的this.print函數。 this.print如何正確知道任何提及this是指test而不是window?通過this.___ = function(){}定義的任何函數是否會自動將this作爲上下文添加?

+1

[JavaScript中的私人成員](http://javascript.crockford.com/private.html) - 閱讀本文。 – dirkgently

+1

對於像我這樣使用coffeescript的人,你可以通過在你的函數中使用'=>'而不是' - >'來像在http://stackoverflow.com/a/10965498/927092中那樣關閉'this'變量'聲明 –

回答

11

this總是 評估爲在對象哪些所述功能對象被調用。它將評估爲window,如果它是「什麼都沒有調用」(或者是window的屬性)。

(注意this不是一個變量,因此在一個封閉封閉了!這就是爲什麼有時候需要關閉,以獲得「正確的」 this這往往是由可變self已知或that_this

,例如:

function f() { return this; } 
var a = {f: f} 
var b = {f: f} 
a.f() === a  // true 
b.f() === b  // true 
f() === window // true 

一種使用可變的實例以創建綁定到的電流(如在調用封閉函數時的)this

test = (function() { 
    var self = this // <-- variable, which is "closed over" 
    this.value = 1; // self === this 
    this.print = function() { 
    console.log(self.value); // <-- self "names" previous this object 
    }; 
    return this; 
})(); 

這是一個小謊言。 Function.callFunction.apply函數允許指定this上下文,並且可以由「上下文綁定」函數使用,例如Function.bind以消除如上所示的顯式「自閉合」的需要。

+0

所以我寫這個的方式,如果我做了'_print = test.print; _print()',它仍然會正確地打印'1',因爲我在關閉中定義了它,這是否正確? –

+1

不, *'_print'調用'this'的計算結果爲'window',因此它將是'window.value'。'this'是* not *變量,因此*不會在閉包中關閉。 print()''將'this'評估爲'test'並因此使用'test.value',這是可以預期的。 – 2012-06-10 00:14:17

+0

所以沒有'test =(function(){...})() ;''''''test'{value:1,print:...}'?無論哪種方式,我都必須在'test'前面加上前綴 –

相關問題