不完全确定为什么一个有效,另一个没有。有人可以解释一下吗?我是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;};
};
答案 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;};
})();
注意函数周围的括号创建一个函数表达式,然后用括号来调用函数。