I tried to write sample code to get understanding of javascript's
prototypal inheritance (along with the variety of function calling
choices.. )
During the process, I got myself throughly confused.
Can anyone explain following behavior [NOTE: Needs firefox+firebug .
otherwise replace all console.* to alert or equivalent]
here is my code:
<html>
<head>
<script type="text/javascript">
function MyClass(){
if(String(this) == '[object Window]'){
console.debug(' Are you sure to use this object in global scope?? Or
you just missed using \'new\' keyword?');
}
this.method = function(){
console.info('i n MyClass.method' );
}
this.param1='pa ram1';
}
function caller(){
var execClsDirectly = MyClass();
var execClsConstruc tor = new MyClass();
// execClsDirectly would be null since MyClass does not have any
return statement
if (execClsDirectl y) execClsDirectly .param2='added global fn call';
execClsConstruc tor.param2='add ed to obj instance';
var clsRef = MyClass;
clsRef.param2=' added to class definition';
MyClass.prototy pe.param2='adde d to class';
console.log('ex ecClsConstructo r param2: '+execClsConstr uctor.param2);
console.log('ou ter param2: '+MyClass.param 2);
var updatedClsConst ructor = new MyClass();
console.log('up datedClsConstru ctor param2:
'+updatedClsCon structor.param2 );
}
</script>
</head>
<body onload="caller( );">
</body>
</html>
the output:
Are you sure to use this object in global scope?? Or you just missed
using 'new' keyword?
execClsConstruc tor param2: added to obj instance
outer param2: added to class definition
updatedClsConst ructor param2: added to class
I of course understand the first line of output, but.. confused as to
same param2 added into MyClass gets added into three different levels.
Can anyone elaborate this?
Hope I was able to articulate my confusion in words...
Regards,
VJ