带有构造函数的Javascript子方法/名称空间
Javascript sub methods / namespacing with constructor functions
我非常感谢您的时间和帮助我搜索了将近两天,找不到确切的答案。开始:
我一直使用对象文字符号来创建我的对象。然而,我最近遇到了一种情况,需要创建同一对象的多个实例。我相信我试图创造的是";构造函数":
我需要有能力创建多个";窗口";对象:
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.
}
}
}
如何尝试使用构造函数和原型构建窗口对象的示例:
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收到以下控制台错误:
- TypeError:Window.errorMessage未定义
- TypeError:Window.errorMessage.show不是函数
非常感谢您的帮助。我很感激。
我仍然会像您尝试的那样在函数的原型上声明您的方法,但您必须在新的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() {}
只有在进行继承时才需要使用prototype
。既然您不是在做继承,那么暂时忘掉prototype
吧。
每个CCD_ 9都有一个CCD_。所以我会这样写:
function Window(id) {
this.id = id;
this.errorMessage = new ErrorMessage();
}
function ErrorMessage() {
this.show = function () {};
this.hide = function () {};
}
var window1 = new Window();
window1.errorMessage.show();
相关文章:
- javascript从子方法调用父方法
- JS对象文字中的方法和子方法
- 从子方法访问父对象
- 如何从子方法调用父方法
- 在 dojo 中使用它通过父类访问子方法
- 要打包的命名空间流星方法
- 带有构造函数的Javascript子方法/名称空间
- 删除变量's的价值而不丢失其子方法
- 如何链接具有命名空间的方法
- 什么's命名空间以及如何从命名空间导出方法
- 用子方法实现函数可以吗
- 我如何从父调用原型子方法
- 从子方法访问父属性
- 带有子方法的方法链接
- 自动css选择器生成的第n子方法的替代方案
- 在Javascript中从子方法调用父方法
- 在JavaScript中从父方法调用子方法
- 如何从子方法中分离父函数
- jQtree,调用嵌套列表中的方法调用父方法和子方法
- Javascript Prototype pub子方法超出作用域