javascript basics - private, instance and global variables and functions
private, instance and global variables and functions
by deshpandeakhil
JavaScript
function classEx(name) {
var pvtVar = "private variable";
globalVar = "global variable";
this.instanceVariable = name;
var pvtFunc = function() {
return "inside private function";
}
globalFunc = function() {
return "inside global function";
}
this.instanceFunction = function() {
return "inside instance function";
}
}
var inst = new classEx("instance variable");
var op = $("#op");
op.append("<b>Variables</b>" + "<br/>");
op.append("inst.pvtVar : " + inst.pvtVar + "<br/>");
op.append("inst.globalVar : " + inst.globalVar + "<br/>");
op.append("globalVar : " + globalVar + "<br/>");
op.append("inst.instanceVariable : " + inst.instanceVariable + "<br/><hr/>");
op.append("<b>Functions</b>" + "<br/>");
try {
op.append("inst.pvtFunc : " + inst.pvtFunc() + "<br/>");
}
catch (err) {
op.append("inst.pvtFunc : " + err + "<br/>");
}
try {
op.append("inst.globalFunc: " + inst.globalFunc() + "<br/>");
}
catch (err) {
op.append("inst.pvtFunc : " + err + "<br/>");
}
op.append("globalFunc : " + globalFunc() + "<br/>");
op.append("inst.instanceFunction : " + inst.instanceFunction() + "<br/><hr/>");
//if we create 3 instances of classEx there will be 3 chunks of code for instanceFunction taking more memory
//that's when we can use the prototype object
op.append("<b>Prototype</b> <br/>");
classEx.prototype.instanceProtoFunction = function(){
return "inside instanceProtoFunction";
}
op.append("inst.instanceProtoFunction : " + inst.instanceProtoFunction() + "<br/>");