javascript - 如何在模块中创建 JavaScript 对象构造函数?

标签 javascript

我正在尝试创建一个可重用的 javascript 对象(我想使用新的)。当我尝试更新我的自定义对象之一时,出现错误:

"org.myorg.sadp.section.sadpSection is not a constructor"

出于 namespace 的原因,我正在模块化我的 JS。我想知道这是否是问题所在:

if (!window.org) var org = { myorg: {} };    
if (!org.myorg) org["myorg"] = { sadp: {} };
if (!org.myorg.sadp) org.myorg["sadp"] = {};

org.myorg.sadp.section = (function(ns) {
    if (ns.section) {
        return ns;
    }
    else {
        ns.section = {};
    }
    ns.section.sadpSection = function(name) {
        this.name = name;
        this.isCompleted = false;
        this.booleanQuestions = new Array();
        this.multipleChoiceQuestions = new Array();
        this.sliders = new Array();
        return true;
    }
    return ns;

} (org.myorg.sadp))

这会导致错误:

var myObj = new  org.myorg.sadp.section.sadpSection("test");

我在这里做错了什么?

谢谢!

最佳答案

您基本上是在使 org.myorg.sadp.section 等于 org.myorg.sadp。这不是你想要的,它基本上是无限递归:

org.myorg.sadp.section == org.myorg.sadp.section.section

无论您添加多少个.section,都是如此。您可以将其更改为:

org.myorg.sadp.section = 
{
    sadpSection: function(name)
    {
        this.name = name;
        this.isCompleted = false;
        this.booleanQuestions = new Array();
        this.multipleChoiceQuestions = new Array();
        this.sliders = new Array();
    }
}

您可以添加:

if(!org.myorg.sadp.section.sadpSection)

避免重新分配构造函数。

这并没有减少模块化。 return true 也是不必要的。

关于javascript - 如何在模块中创建 JavaScript 对象构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5209123/

相关文章:

javascript - 更改人力车图上的数据源/系列

javascript - 如何确定我的页面是在普通浏览器还是 SAP CL_GUI_HTML_VIEWER 中呈现

javascript - Promise-mysql 返回 promise

javascript - CoffeeScript 类 - 调用从另一个类方法调用一个类方法

javascript - $PUSH 到 mongoose 中的 Subdoc 数组中

javascript - Sails.js - 如果我给出未定义的 "id",所有记录都会被销毁

javascript - JavaScript 中的全局变量问题

javascript - 三个jslensflare渲染在外面

javascript - 自动完成 API - jQuery 未定义

javascript - 从 1 个服务执行多个请求 (angularjs)