I define how two functions can inherit from each other as follows:
Function.prototype.inherit = function(parent){
function proto() {}
proto.prototype = parent.prototype;
this.prototype = new proto();
this.prototype.constructor = this;
this.prototype.parent = parent;
}
I then need to define an isInstance function that would behave like Java's instanceOf or PHP's instanceof. In essence, isInstance could be used to determine whether a variable is an instantiated object of a function that inherits from a parent function.
This is what I wrote:
Function.prototype.isInstance = function(func){
if(this == func){
return true;
} else{
if (this.prototype.parent == undefined || this.prototype.parent == null) {
return false;
} else {
return this.prototype.parent.isInstance(func);
}
}
}
Which works fine when comparing two functions, but not when comparing instantiated variables.
Object2.inherit(Object1);
Object2.isInstance(Object1); //returns true
var obj2 = new Object2();
obj2.isInstance(Object1);// obj2.isInstance is not a function
The last case above is what I want to get working. How can I add isInstance to instances, not just functions? And to all javascript gurus out there, are there any improvements to my code (the inherit method, maybe)?
Thanks.