![](/img/trans.png)
[英]Call parent method in JavaScript class but stll have access to prototype methods inside object instance?
[英]Javascript prototype Methods inside object
我正在嘗試創建一個包含其他對象和函數的對象,在原型中,相關部分是 UI 原型;
var fChat = function() {
this.debug = true;
};
fChat.prototype = {
constructor: fChat,
Log: function(str){
if(this.debug){
console.log(str);
}
},
UI: {
Login: {
Show: function(){
this.Log("UI.Login.Show()");
}
}
}
};
var fChatInstance = new fChat();
fChatInstance.UI.Login.Show();
當我調用fChatInstance.UI.Login.Show()
它給我一個錯誤: Uncaught TypeError: this.Log is not a function
那是因為使用this
是在另一個范圍內嗎? 通常我做var self = this;
在原型開始時,但我不知道如何通過使用對象原型來做到這一點。
是的。 問題是this的javascript動態綁定,要修復它,您可以使用bind函數將“this”設置為對象。 像這樣改變 fchat 函數重構它:
var fChat = function() {
this.debug = true;
this.UI.Login.Show = this.UI.Login.Show.bind(this);
this.Log = this.Log.bind(this);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.