相关疑难解决方法(0)

Javascript模块模式有什么好处?

我一直在研究为我的团队提出标准化的Javascript编码风格.现在大多数资源都推荐涉及闭包的"模块"模式,例如:

var Module = function() { 

    someMethod = function() { /* ... */ };

    return { 
        someMethod: someMethod
    };

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

并调用它Module.someMethod();.这种方法似乎只适用于在传统OOP上下文中是静态的方法,例如用于获取/保存数据的存储库类,用于发出外部请求的服务层等.除非我遗漏了某些内容,否则模块模式不适用于通常需要传递给服务方法/从服务方法传递到UI粘合代码的数据类(想想DTO).

我看到的一个常见好处是你可以在Javascript中使用模块模式获得真正的私有方法和字段,但这也可以实现,同时能够使用类似于此的"经典"Javascript样式的静态实例方法:

myClass = function(param) { 
    // this is completely public
    this.publicProperty = 'Foo';

    // this is completely private
    var privateProp = param;

    // this function can access the private fields
    // AND can be called publicly; best of both?
    this.someMethod = function() { 
        return privateProp;
    };

    // this function is private.  FOR INTERNAL …
Run Code Online (Sandbox Code Playgroud)

javascript

8
推荐指数
1
解决办法
2187
查看次数

标签 统计

javascript ×1