This is a follow-up to my previous query. I have been trying some code since then :
var myFunc = function(){
this.int1=1;
var int2=2;
};
myFunc.int1=3;
myFunc.int3=4;
for(var name in myFunc){
console.log('myFunc...'+name+'='+myFunc[name]);
};
var myFuncImpl = new myFunc();
myFuncImpl.int1=5;
for(var name in myFuncImpl){
console.log('myFuncImpl...'+name+'='+myFuncImpl[name]);
};
And I get output as :
myFunc...int1=3
myFunc...int3=4
myFuncImpl...int1=5
I can’t answer the following questions :
-
Why isn’t int2 visible as a property to myFunc ? It’s still in myFunc’s scope, right ? Where does this definition disappear ?
-
Why I am I able to over-write int1‘s value outside function scope ? What if someone accidentally deletes my values outside code ? For “objects”, I understand “Object.freeze()” can help over myFuncImpl – but what about function definitions like myFunc ?
-
Why can’t I access int3 from myFuncImpl ? Where did the prior definition (while defining myFunc) go ?
I guess my doubts are due to my thinking of myFunc as a “class” (as in Java) and myFuncImpl as an object. Perhaps I am straying too far ?
Thanks !
int2is effectively a private variable, so code outside the function cannot detect it http://javascript.crockford.com/private.htmlThis is just a fact of life with “vanilla” JS. if you need to prevent overwriting values, implement with
Object.defineProperty. Caveats with IE<9int3is a ‘static’ property to the function. It is not available on the instance, sort of like in C# if you have a static method, it’s not available to instances of the class. The difference here is you can later on in your code saymyFunc.int1 = "asdf";and now your ‘static’ property has changed. Don’t confuse static with constanthttp://elegantcode.com/2011/01/19/basic-javascript-part-7-static-properties-and-methods/