非常感谢您的时间和帮助!我已经搜索了近 2 天,但找不到确切的答案。开始:
我一直使用对象文字表示法来创建我的对象。然而,我最近遇到了一种情况,我需要创建同一对象的多个实例。我相信我试图创建的是“构造函数”:
我需要能够创建多个“Window”对象:
var window1 = new Window();
var window2 = new Window();
var window3 = new Window();
我希望能够组织这样的方法:
window1.errorMessage.show();
window2.errorMessage.hide();
window3.errorMessage.hide();
而不是类似:
window1.showErrorMessage();
window2.hideErrorMessage();
window3.hideErrorMessage();
如何用文字表示法构建窗口对象的示例:
var Window = {
id: null,
init : function(id) {
this.id = id;
},
errorMessage : {
show : function(message) {
// jquery that will simply take the id of this window,
// find the errorMessage html element within the window,
// insert the "message" and show it.
},
hide : function() {
// jquery that will simply take the id of this window,
// find the errorMessage html element within this window and hide it.
}
}
}
我如何尝试使用构造函数和原型(prototype)构建窗口对象的示例:
function Window(id) {
this.id = id;
this.errorMessage = function() {}
}
Window.prototype.errorMessage = function() {}
Window.errorMessage.prototype.show = function(message) {
// jquery that will simply take the id of this window,
// find the errorMessage html element within the window,
// insert the "message" and show it.
}
Window.errorMessage.prototype.hide = function() {
// jquery that will simply take the id of this window,
// find the errorMessage html element within this window and hide it.
}
当我尝试执行以下代码时:
var window1 = new Window();
window1.errorMessage.show('An error message');
(最终我想使用它来调用它:)
this.errorMessage.show('An error message');
我从 Firefox 收到以下控制台错误:
- 类型错误:Window.errorMessage 未定义
- TypeError:Window.errorMessage.show 不是函数
非常感谢您的帮助。我很感激。
最佳答案
我仍然会像您尝试的那样在函数原型(prototype)上声明您的方法,但您必须在新的 ErrorMessage< 上声明
类型。我认为这样的事情是最好和最有效的(因为 show
和 hide
方法ErrorMessage
的实例将共享相同的 show
和 hide
方法) (如果我正确理解您的需求)。
function Window(id) {
this.id = id;
this.errorMessage = new ErrorMessage();
}
function ErrorMessage() { }
ErrorMessage.prototype.show = function() {}
ErrorMessage.prototype.hide = function() {}
关于带有构造函数的 Javascript 子方法/命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18494101/