不完全确定为什么一个有效而另一个无效。有人可以解释一下吗?我是 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;};
};
最佳答案
尝试将其视为 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/