2012-10-01 150 views
0

可能重複:
「this」 keyword in event methods when using JavaScript prototype object從另一個成員函數調用成員函數在JavaScript

我創建了一個名爲「MyClass的」在JavaScript類和約束onclick事件到按鈕上這一頁。當onclick事件觸發時,我想調用另一個成員函數,但它給了我一個未定義的錯誤。請幫忙。

//MyClass constructor 
MyClass = function() { 

//Find search button 
this.ctrlSearchButton = $("#btnSearch"); 

//Attach onclick event to search button 
this.ctrlSearchButton.click(this.onSearchButtonClick); 
}; 

MyClass.prototype.onSearchButtonClick = function() { 
    DoSearch();// ERROR : Object Expected 
}; 

MyClass.prototype.DoSearch = function() { 
    alert("search called"); 
}; 
+0

幫我:http://stackoverflow.com/a/4947449/470749 – Ryan

回答

0
MyClass = function() { 
    var self = this; 
    this.onSearchButtonClick = function() { 
     self.DoSearch();// ERROR : Object Expected 
    }; 
    this.DoSearch = function() { 
     alert("search called"); 
    }; 
    .... 
} 
+0

其實你很可能只是移動MyClass.prototype聲明到MyClass的=功能()方法,這樣你就可以無需自我聲明即可訪問此內容 – Betty