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

标签 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

最佳答案

尝试将其视为 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;};
})();

请注意函数周围的括号以创建函数表达式,以及其后面的括号以调用该函数。

关于javascript - JS封装问题: "this.foo = new function(){...};" vs "this.Bar = function(){..}; this.foo = new Bar();",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24458839/

相关文章:

javascript - Angular 4 - 具有动态参数值的自定义验证器

javascript - 为什么我的 JS for 循环不工作? (返回 "undefinded"

javascript - JavaScript 上下文中的封装是什么?

javascript - 谁能告诉我为什么我的按钮不显示内容?

javascript - 重构 Angular Controller

javascript - 单击按钮以指定的时间间隔更改颜色

php - 使用按位或将数组中的标志组合为单个值

C++ - 基本功能问题

javascript - 原型(prototype)和 document.getElementById()

python - 什么时候在 Python 中初始化静态变量?