我有JavaScript組件,即具有以下結構:這個指針從內部功能
var MyComponent = function(params)
{
setup(params);
this.doSomething()
{
// doing something
};
function setup(params)
{
// Setup
// Interaction logic
var _this = this; // "this" points to DOMWindow, not to created object
$(".some-element").click(function(){
_this.doSomething(); // it craches here, because of above
});
}
};
當某物,由交互邏輯控制,情況發生時,有時我必須轉發組件的執行爲「公衆」的方法。
在這種情況下,我對「this」指針有問題。
示例代碼演示了:
var Item = function()
{
this.say = function()
{
alert("hello");
};
this.sayInternal = function()
{
_sayInternal();
};
function _sayInternal()
{
this.say();
};
};
爲了測試它,
- 創建一個對象:
var o = new Item();
- 這工作正常:
o.say(); // alerts "hello"
- 這種崩潰:
o.sayInternal();
我得到一個錯誤:
TypeError: Result of expression 'this.say' [undefined] is not a function.
我認爲,這樣的行爲發生,因爲_sayInternal ( )函數聲明爲(並未分配給對象,如「this.say = function()」)。這樣,它就在所有創建的對象之間共享,並像C++中的靜態函數一樣工作。
這是真的嗎?
謝謝!很好的解釋! – AntonAL 2011-02-15 10:23:25