用JavaScript创建模块和类

时间:2014-07-02 21:56:19

标签: javascript

我试图在JavaScript中创建一个模块。我希望我的模块有类似课程的东西。我不确定我尝试的是否可行。基本上,我希望能够在JavaScript中执行此操作:

var myObject = new myCompany.myLibrary.myClass();
myObject.myFunction();

目前,我正在尝试以下方法:

var myCompany = myCompany || {};
myCompany.myLibrary = (function() {    
    var myProperty = null;

    var anotherProperty = 'Hello';

    return {
        myClass: function () {
          return {
            myFunction : function() {
              console.log(anotherProperty);
            }
          };
        }
    };
})();

当我这样做时,我收到错误,上面写着" undefined不是函数"。是否有可能做我想在JavaScript中完成的事情?如果是这样,我做错了什么?

2 个答案:

答案 0 :(得分:0)

此代码在我运行时有效。你能发布一个工作(呃,破碎)例子的链接吗?


顺便说一句,由于您要返回一个对象,因此您不需要new运算符。这有效:

myCompany.myLibrary.myClass().myFunction(); // Logs "Hello"

如果 使用new,则无需返回新对象。您可以将myClass的正文更改为以下内容:

this.myFunction = function() {
    console.log(anotherProperty);
};

对于它的价值,我建议不要试图模仿私人成员,并写下你的例子:

var myCompany = myCompany || {};

myCompany.myLibrary = {
    myProperty: null,
    anotherProperty: 'Hello',
    myClass: (function() {
        function myClass() {}
        myClass.prototype.myFunction = function(){
            console.log(myCompany.myLibrary.anotherProperty);
        }
        return myClass;
    })()
};

答案 1 :(得分:-1)

这个怎么样:

var MyCompany = MyCompany || {}; // Namespace
MyCompany.MyLibrary = function() { // this becomes the constructor   
    var mylib = this; // grab a ref to this, as it is context specific and not a good idea to use later.
    mylib.myProperty = null; // your first prop
    mylib.anotherProperty = 'Hello'; // your second prop

    // Returns an object that is actually not the object being "new'ed up", 
    // but will provide protection to everything inside it.  One of many ways 
    // to skin the cat.  I kept the code as close to the OPs code to get what he wants.
    // This isnt a class in how to write the best JS.
    return {
        myFunction : function() {
            console.log(mylib.anotherProperty);
        }
    };
};

var myLibrary = new MyCompany.MyLibrary();
myLibrary.myFunction();