JS封装问题:" this.foo = new function(){...};" vs" this.Bar = function(){..}; this.foo = new Bar();"

时间:2014-06-27 18:43:21

标签: javascript function oop encapsulation

不完全确定为什么一个有效,另一个没有。有人可以解释一下吗?我是JavaScript的新手。到目前为止,我一直在阅读this guide

这有效。数据被认为是_fSettings对象的局部变量。

ENTRANCE_APP._fSettings = function(){
    var data = new StorageObject('settings');
    /** The selected camera index. **/
    var cameraIndex = data.getValue('cameraIndex','0');
    this.setCameraIndex = function(index)   {cameraIndex = index;};
    this.getCameraIndex = function()    {return cameraIndex;};
};
ENTRANCE_APP.settings = new ENTRANCE_APP._fSettings();

但这不是吗?在第一次声明之后,数据被认为是一个全局变量。所以' data.getValue(...)'将数据视为全局变量。

ENTRANCE_APP.settings = new function(){
    var data = new StorageObject('settings');
    /** The selected camera index. **/
    var cameraIndex = data.getValue('cameraIndex','0');
    this.setCameraIndex = function(index)   {cameraIndex = index;};
    this.getCameraIndex = function()    {return cameraIndex;};
};

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试将其视为IIFE,如下所示:

ENTRANCE_APP.settings = new (function(){
    var data = new StorageObject('settings');
    /** The selected camera index. **/
    var cameraIndex = data.getValue('cameraIndex','0');
    this.setCameraIndex = function(index)   {cameraIndex = index;};
    this.getCameraIndex = function()    {return cameraIndex;};
})();

注意函数周围的括号创建一个函数表达式,然后用括号来调用函数。