javascript - JS encapsulation issue: "this.foo = new function(){...};" vs "this.Bar = function(){..}; this.foo = new Bar();" -
not entirely sure why 1 works , other not. please explain this? i'm new javascript. i've been reading this guide far.
this works. data considered local variable of _fsettings object.
entrance_app._fsettings = function(){ var data = new storageobject('settings'); /** 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();
but not? data considered global variable after first declaration. 'data.getvalue(...)' treats data global variable.
entrance_app.settings = new function(){ var data = new storageobject('settings'); /** selected camera index. **/ var cameraindex = data.getvalue('cameraindex','0'); this.setcameraindex = function(index) {cameraindex = index;}; this.getcameraindex = function() {return cameraindex;}; };
try treating iife this:
entrance_app.settings = new (function(){ var data = new storageobject('settings'); /** selected camera index. **/ var cameraindex = data.getvalue('cameraindex','0'); this.setcameraindex = function(index) {cameraindex = index;}; this.getcameraindex = function() {return cameraindex;}; })();
notice parentheses surrounding function create function expression , parentheses after invoke function.
Comments
Post a Comment