具有命名空间的JavaScript匿名函数的优点

jcr*_*898 6 javascript

编写JavaScript类和命名空间时有什么好处......

if(typeof MyNamespace === 'undefined'){
    var MyNamespace = {};
}

(function(){
MyNamespace.MyClass = function(){
    this.property = 'foo'

    return this;
}
}());
Run Code Online (Sandbox Code Playgroud)

与此相关......

if(typeof MyNamespace === 'undefined'){
    var MyNamespace = {};
}

MyNamespace.MyClass = function(){
    this.property = 'foo'

    return this;
}
Run Code Online (Sandbox Code Playgroud)

我已经看到在少数库中实现的第一个模式,并试图找出如果有任何额外的好处,除非在第一个示例中的匿名函数内部声明了某种其他函数.

Dem*_*cht 11

对于你的问题:

是的,存在差异(和利益).在第一个示例中,您可以控制访问控制(意味着使用基于原型的公共/私有成员变量和函数版本).举个例子:

var m = (function() {
    var o = {};
    o.myPublicProperty = 0; // can be accessed by instantiated object's calling code

    var myPrivateProperty = 1; // can't be accessed outside of this module

    o.myPublicFunction = function() {
        myPrivateFunction();
        return myPrivateProperty;
    };

    function myPrivateFunction() {
        ++myPrivateProperty;
        ++o.myPublicProperty;
    }

    o.getMyPrivateProperty = function() {
        return myPrivateProperty;
    }

    return o;
})();

console.log(m.myPublicProperty);       // 0
console.log(m.getMyPrivateProperty()); // 1
console.log(m.myPrivateProperty);      // undefined
console.log(m.myPublicFunction());     // increments
console.log(m.myPublicProperty);       // 1
console.log(m.getMyPrivateProperty()); // 2
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/dbrecht/EQ4Tb/

有点偏离主题,但这对我来说有点奇怪:

if(typeof MyNamespace === 'undefined'){
    var MyNamespace = {};
}
Run Code Online (Sandbox Code Playgroud)

为什么不使用:var MyNamespace = MyNamespace || {};

  • 我喜欢这个var MyNamespace = MyNamespace || {}; 好多了...谢谢! (2认同)