D
Dolaameng
Hi, guys, I am a newbie to javascript. I'd like to find out how the
'instanceof' operator works in javascript? What kind of tests are
going on behind the scene? For example, in following code, I
constructed a 'Base' class, and a 'Derived' class to extend it. Then I
instantiate an instance of 'Derived' to test if it is 'instanceof' the
Base class:
<script type="text/javascript">
//<![CDATA[
function extend(SubClass, SupClass){
var F=function(){};
F.prototype=SupClass.prototype;
SubClass.prototype=new F();
SubClass.prototype.constructor=SubClass;
//...
}
var Base=function(){};
//Base.prototype={};
var Derived=function(){
//Base.apply(this,null);
};
extend(Derived,Base);
var d=new Derived();
alert(d instanceof Base); //true
//]]>
</script>
The instanceof test above evaluates to true, with no surprise. I
guess this is because the interpreter found that
'Derived.prototype.prototype.constructor' is now 'Base'. So I add a
new line of code
Base.prototype={}
between the definition of Base and Derived class. This time I know
that 'Base.prototype.constructor' is not 'Base' anymore, it has been
overwritten to 'Object' instead. But superisely 'd instanceof Base'
still evaluates to true. Why does this magic happen?
'instanceof' operator works in javascript? What kind of tests are
going on behind the scene? For example, in following code, I
constructed a 'Base' class, and a 'Derived' class to extend it. Then I
instantiate an instance of 'Derived' to test if it is 'instanceof' the
Base class:
<script type="text/javascript">
//<![CDATA[
function extend(SubClass, SupClass){
var F=function(){};
F.prototype=SupClass.prototype;
SubClass.prototype=new F();
SubClass.prototype.constructor=SubClass;
//...
}
var Base=function(){};
//Base.prototype={};
var Derived=function(){
//Base.apply(this,null);
};
extend(Derived,Base);
var d=new Derived();
alert(d instanceof Base); //true
//]]>
</script>
The instanceof test above evaluates to true, with no surprise. I
guess this is because the interpreter found that
'Derived.prototype.prototype.constructor' is now 'Base'. So I add a
new line of code
Base.prototype={}
between the definition of Base and Derived class. This time I know
that 'Base.prototype.constructor' is not 'Base' anymore, it has been
overwritten to 'Object' instead. But superisely 'd instanceof Base'
still evaluates to true. Why does this magic happen?