I was experimenting with inheritance in javascript, and wrote those two functions:
Object.prototype.inherits=function(obj){this.prototype=new obj;}
Object.prototype.pass=function(obj){obj.prototype=new this;}
This code works very well:
Dog.inherits(Animal);
But the following fails:
Animal.pass(Dog);
As I understand it, my pass functions doesn’t work, because “this” isn’t a reference to the object instance itself? If that’s the case, how can I reference the object from within itself?
Thanks in advance!
Well, actually the two are doing exactly the same:
The
thisvalue inside the methods will refer to the base object where the reference was invoked, in the case of:The
thisvalue will refer to theDogconstructor function, and theobjargument will be theAnimalfunction.When you call:
The
thisvalue will refer to theAnimalfunction, doing at the end exactly the same thing as theinheritsmethod, but the other way around.I would recommend you to not extend the
Object.prototypeobject, because it can cause you a lot of problems, for example those two properties will be enumerated in anyfor-inloop, e.g.:All objects inherit from
Object.prototype, and it seems that you intend to use those methods only on Function objects, it would be safer to extend theFunction.prototypeobject, or implement the methods as functions that take two parameters.