【问题标题】:JS encapsulation issue: "this.foo = new function(){...};" vs "this.Bar = function(){..}; this.foo = new Bar();"JS 封装问题:“this.foo = new function(){...};”与“this.Bar = function(){..}; this.foo = new Bar();”
【发布时间】:2014-06-27 18:43:21
【问题描述】:

不完全确定为什么一个有效而另一个无效。有人可以解释一下吗?我是 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;};
};

【问题讨论】:

    标签: javascript function oop encapsulation


    【解决方案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;};
    })();
    

    注意函数周围的括号以创建函数表达式,并注意它后面的括号以调用函数。

    【讨论】:

    • i.stack.imgur.com/oJp9o.jpg 好的。尝试了您的解决方案,数据仍然在 IDE 中突出显示为未声明的全局变量。也许这是我的 IDE 的问题?
    • 请注意,jslint 根本不喜欢这个,如果你喜欢这种东西的话。构造 var foo = new (function () {})(); 将报告“将调用移动到包含函数的括号中。”。但在这种情况下,构造 var foo = new (function () {}()); 是语法错误。为了获得有用的堆栈跟踪,我强烈建议您将函数命名为 function EntranceAppSettings() {},并像 ENTRANCE_APP.settings = new EntranceAppSettings() 一样调用它。
    • @TaylorLove 我不确定你使用的是什么 IDE,但它警告你一个未声明的变量在该变量的声明中.
    • @JoeFrambach 我同意这一点。 OP 的原始解决方案似乎更清洁。
    • @JoeFrambach 尤里卡!乔,你是对的。命名函数似乎解决了我一直遇到的问题。我使用的 NETBEANS IDE 似乎不喜欢以这种方式使用未命名的函数。所以给它一个名字可以修复警告。谢谢一百万,先生! i.stack.imgur.com/wR2NC.jpg
    猜你喜欢
    • 2011-03-30
    • 2019-11-03
    • 2021-12-21
    • 2015-11-15
    • 2019-03-22
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多