具有命名空间的JavaScript匿名函数的优点 [英] Benefits of JavaScript anonymous function with namespaces

查看:81
本文介绍了具有命名空间的JavaScript匿名函数的优点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any benefit when writing JavaScript classes and namespaces of this...

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

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

    return this;
}
}());

这就是......

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

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

    return this;
}

我看过第一个模式在几个库中实现,并试图除非在第一个例子中的匿名函数内部声明了某种其他函数,否则如果有任何额外的好处会发现如何。

I have seen the first pattern implemented in a few libraries, and was trying to find how out if there is any added benefit unless some sort of other function was declared inside of the anonymous function in the first example.

推荐答案

问题:

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

Yes, there is a difference (and benefit). In your first example, you can control access control (meaning using prototype-based version of public/private member variables and functions). As an example:

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

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

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

A little off topic, but this is a little strange to me:

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

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

这篇关于具有命名空间的JavaScript匿名函数的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆