带有构造函数的Javascript子方法/名称空间

Javascript sub methods / namespacing with constructor functions

本文关键字:空间 子方法 Javascript 构造函数      更新时间:2023-09-26

我非常感谢您的时间和帮助我搜索了将近两天,找不到确切的答案。开始:

我一直使用对象文字符号来创建我的对象。然而,我最近遇到了一种情况,需要创建同一对象的多个实例。我相信我试图创造的是";构造函数":

我需要有能力创建多个";窗口";对象:

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类型上声明showhide方法。我认为这样做是最好、最有效的(因为ErrorMessage的实例都将共享相同的showhide方法)(如果我正确理解您的需求)。

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();