JSFiddle - React, Tailwind, and code Playground
by Josh Weir
JavaScript
/*
///////////
//Closures
///////////
const myModule = (function(){
let _privateFoo = 'foo',
getFoo = () => _privateFoo,
setFoo = foo => _privateFoo = foo,
concatFoo = withVal => _privateFoo + withVal;
return {
getFoo, concatFoo, setFoo
};
})();
const { getFoo, setFoo, concatFoo } = myModule;
console.log(getFoo(), '//foo');
setFoo('bar');
console.log(getFoo(), '//bar');
console.log(concatFoo('baz'), '//barbaz');
////////////////////////
//lexical scope example
////////////////////////
var outer = 'outer';
lexicalEg = function() {
console.log(outer, 'l1 output: outer');
return function() {
console.log(outer, 'l2 output: outer');
}
};
lexicalEg()();
const func1 = (() => {
var _private = 1;
return () => _private += 1
})();
const func2 = func1;
console.dir(func1);
document.writeln(func1());
document.writeln(func2());
*/
//if you only need a single instance of an object can do this:
var obj = {
myvar: 2,
getvar: function() {console.log(this.myvar);}
};
obj.getvar();
//but now there is public access to it's variables:
obj.myvar = 3;
obj.getvar();
//so better to use the module pattern:
var objModule = (function(){
var _myvar = 5,
getvar = function() {console.log(_myvar)};
return {
getvar: getvar
};
})();
objModule.getvar(); //can access the private variable (closure) through public method
//but if I need to create many instances of an object, better to use the constructor in combination with prototype to save on memory:
function Obj(myvar) {
this.myvar = myvar;
}
//implementing getvar on the object prototype will ensure that only a single instance of the getvar function is instantiated even with multiple instances of Obj - saving memory:
Obj.prototype.getvar = function() {console.log(this.myvar);};
/*
note that this could also be written like this:
Obj.prototype = {
getvar: function() {console.log(this.myvar);}
}
or:
parentObj = {
getvar: function() {console.log(this.myvar);}
};
Obj.prototype = parentObj;
so we see how...