如何正确设置 JavaScript 命名空间和类

How to set up JavaScript namespace and classes properly?

本文关键字:命名空间 JavaScript 何正确 设置      更新时间:2024-02-24

似乎有很多方法可以设置JavaScript应用程序,因此对于哪种是正确的或最好的方法感到困惑。以下技术是否有任何区别或更好的方法?

MyNamespace.MyClass = {
    someProperty: 5,
    anotherProperty: false,
    init: function () {
        //do initialization
    },
    someFunction: function () {
        //do something
    }
};
$(function () {
    MyNamespace.MyClass.init();
});

另一种方式:

MyNamespace.MyClass = (function () {
    var someProperty = 5;
    var anotherProperty = false;
    var init = function () {
        //do something
    };
    var someFunction = function () {
        //do something
    };
    return {
        someProperty: someProperty
        anotherProperty: anotherProperty
        init: init
        someFunction: someFunction
    };
}());
MyNamespace.MyClass.init();

第一种技术感觉更像是一堂课。如果这有所作为,我来自服务器端背景。第二种技术似乎更多余且有点尴尬,但我认为它也经常使用。有人可以帮忙阐明一些问题并建议前进的最佳方式吗?我想创建一个应用程序,其中包含许多类相互通信。

这些都不做。

创建一个JavaScript"类":

var MyClass = function () {
    var privateVar; //private
    var privateFn = function(){}; //private 
    this.someProperty = 5;  //public
    this.anotherProperty = false;  //public
    this.someFunction = function () {  //public
        //do something
    };
};
MyNamespace.MyClass = new MyClass();

一个带有静态变量:

var MyClass = (function(){
    var static_var; //static private var
    var MyClass = function () {
        var privateVar; //private
        var privateFn = function(){}; //private 
        this.someProperty = 5;  //public
        this.anotherProperty = false;  //public
        this.someFunction = function () {  //public
            //do something
        };
    };
    return MyClass;
})();
MyNamespace.MyClass = new MyClass();

使用"构造函数">

(所有示例都有一个"构造函数",这个示例只有可以使用的参数(:

var MyClass = function (a, b c) {
    //DO SOMETHING WITH a, b, c <--
    var privateVar; //private
    var privateFn = function(){}; //private 
    this.someProperty = 5;  //public
    this.anotherProperty = false;  //public
    this.someFunction = function () {  //public
        //do something
    };
};
MyNamespace.MyClass = new MyClass(1, 3, 4);

通过上述所有操作,您可以执行以下操作

MyNamespace.MyClass.someFunction();

你不能做(从外面(:

MyNamespace.MyClass.privateFn(); //ERROR!

第一个示例只是一个 Object 文本 - 它不能实例化并且没有私有成员。第二个例子有一些不正确的语法(var someProperty: 5应该var someProperty = 5(,但使用闭包将内部私有状态封装在一个自调用的匿名函数中。

第二种方法看起来更适合封装私有成员,但可以通过使其成为可实例化的类来使其更加"面向对象":

MyNamespace.MyClass = function() { ... };
MyNamespace.MyClass.prototype.someProperty = 'foo';

然后,您可以使用"new"关键字实例化它:

var aClass = new MyNamespace.MyClass();
aClass.init(...);

我对具有命名空间的可实例化类使用以下语法

 var MYNamespace = MYNamespace|| {};
 MYNamespace.MyFirstClass = function (val) {
        this.value = val;
        this.getValue = function(){
                          return this.value;
                       };
    }
var myFirstInstance = new MYNamespace.MyFirstClass(46);
alert(myFirstInstance.getValue());

JSFIDDLE: http://jsfiddle.net/rpaul/4dngxwb3/1/

为什么永远不应该使用

 return { methodName : methodDelegate}

就像第二个例子一样:

MyNamespace.MyClass = (function () {
    var someProperty = 5;
    var init = function () {
        //do something
    };
    return {
        someProperty: someProperty
        someFunction: someFunction
    };
}());
MyNamespace.MyClass.init();

当你使用命名空间时,你必须把它看作是关于声明,而不是实例。

MyNamespace = {};
MyNamespace.sub = {};
MyNamespace.anotherSub = {};
MyNamespace.sub.MyClass = (function () {
    var static_var; //static private var
    var MyClass2 = function () {
        var privateVar; //private
        var privateFn = function () { }; //private 
        this.someProperty = 5;  //public
        this.anotherProperty = false;  //public
        this.someFunction = function () {  //public
            //do something
        };
    };
    return MyClass2;
})();
debugger;
var c1 = new MyNamespace.sub.MyClass();
c1.someProperty = 1; // creates 5->1.
var c2 = new MyNamespace.sub.MyClass();
c2.someProperty = 2;  // creates 5->2. c1 is still 1

debugger;
var myClass = function () {
    var someProperty = 5;
    var anotherProperty = false;
    var init = function () {
        //do something
    };
    var someFunction = function () {
        //do something
    };
    return {
        someProperty: someProperty,
        anotherProperty: anotherProperty,
        init: init,
        someFunction: someFunction
    };
};

MyNamespace.MyClass = myClass();
var c2 = MyNamespace.MyClass;
// how  are planning to create one more object, while it's a reference? copy      //the whole one?
c2.someProperty = 2; // changes 5 -> 2
var c3 = MyNamespace.MyClass.init(); // create 2 instead of 5
c3.someProperty = 3;    // changes c3 and c3 from 2 to 3.
console.log(c2.someProperty + c3.someProperty);

而且没有达到多少模块防拍的流行程度。声明使您能够以其他开发人员预期的方式将相同的代码用于不同的实例。代码的质量和读取的简单性提高了。任何开发人员的目标都是编写要读取的简单代码,而不是较短或 D.R.Y。 - 但易于阅读并被其他开发人员理解。这首先减少了错误的数量。(c( S. 麦康奈尔

如何组合命名空间和类声明:

var ns = { // your namespace
    my_value: 1, // a value inside the namespace to avoid polluting
    MyClass: function() { // a class inside the namespace
        this.class_property: 12,
        this.class_method: function() {
            console.log("My property: " + this.class_property);
        }
    },
    myFunction: function() { // a function inside a namespace
        console.log("I can access namepsace value if you don't use 'new': " + this.my_value);
    }
};

获取您的价值:

console.log(ns.my_value);

现在,对于类和函数:如果您使用 new ,函数中的单词 this 将指向它的构造函数。如果不使用 newthis将指向命名空间。所以

使用类:

var obj = new ns.MyClass();

使用该函数:

ns.myFunction();

如果在没有 new 的情况下构造对象,this将指向命名空间,因此命名空间将被"销毁",因为MyClass.class_propertyMyClass.class_method将被添加到其中。