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

标签 javascript object-literal

非常感谢您的时间和帮助!我已经搜索了近 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< 上声明 showhide 方法 类型。我认为这样的事情是最好和最有效的(因为 ErrorMessage 的实例将共享相同的 showhide 方法) (如果我正确理解您的需求)。

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/

相关文章:

javascript - AngularJS 1.4.3 ngRepeat 在具有隔离范围的指令中使用时打印 {{ variableName }} 而不是值

javascript - 如何在 JavaScript 对象文字中使用变量作为键?

javascript - 嵌套文字对象并按小写过滤

javascript - Javascript 文字对象中的私有(private)变量

Javascript 在函数内部使对象字面量等于 {},

javascript - 需要对象字面量函数中 switch case 的默认值的等效项

javascript - 使用 jQuery 设置单选按钮的值

javascript - 解析 JSON 中的错误消息失败

javascript - firebase auth().onAuthStateChanged 是否执行提取?

javascript - 与 python-shell 和 node.js 的双向通信