Advanced Javascript: The Alt Way To Do Pub/priv In Js - Is A Mystery
Solution 1:
Using private instance variables prevents you from using prototype (functions that need to access them need to be in the constructor body where the privates are declared with var
) at the end of this answer is link to a pattern that implements protected. It may take some time to understand how prototpe works and would advice trying to understand the basic workings first before trying to mix it with closures to simulate private/public modifier.
Pointy answered you question correctly that when invoking a function with new
but then returning an object would not return the Object referred to as this
in the function:
functionTest(){
this.name="some test";
return {name:"something else"};
}
console.log((newTest()).name);//name:something else
Not returning an object or returning a primitive (string, boolean, number) would cause the this
object to be returned:
functionTest(){
this.name="some test";
return"hello";
}
console.log((newTest()).name);//name:some test
Solution 2:
Your constructor is returning a different object than the one build implicitly with new
. Thus, inside the constructor this
refers to a different object than the one you actually end up with outside, and that object doesn't have a property called "logSetting_priv".
Post a Comment for "Advanced Javascript: The Alt Way To Do Pub/priv In Js - Is A Mystery"