Function variables
by Mahesha999
JavaScript
/**********************************************************************************
This JSFiddle explains different ways to define members on the function and how
these members behave. It explains by defining variables as members, though the
behavior should be same if you define methods.
May not work in some browsers like IE. Better try on Chrome or Opera.
Why? You will understand as you go on reading. :)
**********************************************************************************/
function tempFun(arg1,arg2) {
this.val1 = arg1;
var val2 = arg2;
//Below methods become instance methods when tempFun is
//is invoked as `new tempFun()`, since `new` makes
//`this` inside `tempFun` to point the instance
//being constructed, thus adding function to the
//instance.
//These instance methods are the only way to expose
//closure variable val2 to the outside world of the function
this.getLocalVar = function(){
return val2;
};
this.setLocalVar = function (arg) {
val2 = arg;
};
}
tempFun.prototype.val3 = "fun.proto.var3";
tempFun.val4 = "fun.var4";
var objTempFun1 = new tempFun("this.var1x","var var2x");
var objTempFun2 = new tempFun("this.var1y","var var2y");
/*-----------------------------------------------------------------------
Variables defined as `this.variableName` (val1)
[1] Gets added to function instance when created as `new functionName()`
[2] Have separate values across instances
[3] Cannot be accessed through function directly
-----------------------------------------------------------------------*/
document.write("<br />obj1-this.var1: " + objTempFun1.val1 + "<br />");
document.write("obj2-this.var1: " + objTempFun2.val1 + "<br />");
document.write("fun-this.var1: " + tempFun.val1 + "<br />"); //[3]
objTempFun1.val1 = "this.var1xx";
objTempFun2.val1 = "this.var1yy";
document.write("obj1-this.var1: " + objTempFun1.val1 +...