[英]Javascript prototype Methods inside object
I'm trying to create an Object containing other Objects and functions, in a prototype, the relevant part is the UI prototype;我正在尝试创建一个包含其他对象和函数的对象,在原型中,相关部分是 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();
When i call fChatInstance.UI.Login.Show()
It give me an error: Uncaught TypeError: this.Log is not a function
当我调用
fChatInstance.UI.Login.Show()
它给我一个错误: Uncaught TypeError: this.Log is not a function
Is that because by using this
is on another scope?那是因为使用
this
是在另一个范围内吗? Usually i do var self = this;
通常我做
var self = this;
at the start of a prototype, but i don't know how I can do that by using an Object prototype.在原型开始时,但我不知道如何通过使用对象原型来做到这一点。
Yes.是的。 The problem is the javascript dynamic binding of this, to fix it you can set "this" to the object by using bind function.
问题是this的javascript动态绑定,要修复它,您可以使用bind函数将“this”设置为对象。 Change the fchat function refactor it like 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.