Can someone please explain the following code? Why don't the inner functions access the "inside" variable within the same parent function - yet they seem to share the same variable with peer functions? I know that I could use "this" from within the child functions to access the "inside" variable in the parent function, but I'm puzzled as to why this is needed.... Have I effectively been creating class instances when I probably want something more static? I've been using this pattern to wrap javascript functionality, but now I'm wondering if there is a better/easier pattern that avoids this challenge of variable encapsulation (something more static)? Thank you for your insights.
var wrap = function() {
var inside = null;
function showInside() {
console.log(inside);
}
function changeInside() {
console.log(inside);
inside += 'test';
}
return {
inside: inside,
showInside: showInside,
changeInside: changeInside
};
}();
wrap.changeInside();
wrap.showInside();
wrap.changeInside();
wrap.showInside();
console.log(wrap.inside);
var foo = 42; var obj = {foo: foo}; foo = 21; console.log(obj.foo);. JavaScript is pass by value.{foo: foo}assigns a copy of the value offooto the propertyfoo.foowas an object, you would not assign a copy of the object but a copy of the reference to the object.