gpt4 book ai didi

对象内部的 Javascript 原型(prototype)方法

转载 作者:行者123 更新时间:2023-11-30 00:26:35 26 4
gpt4 key购买 nike

我正在尝试创建一个包含其他对象和函数的对象,在原型(prototype)中,相关部分是 UI 原型(prototype);

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() 时,它给我一个错误:未捕获的类型错误:this.Log 不是一个函数

那是因为在另一个范围内使用 this 吗?通常我会在原型(prototype)的开头执行 var self = this;,但我不知道如何使用对象原型(prototype)来做到这一点。

最佳答案

是的。问题是 this 的 javascript 动态绑定(bind),要修复它,您可以使用绑定(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);
};

关于对象内部的 Javascript 原型(prototype)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31208984/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com