Perhaps I’m doing this wrong. I want to set up a base class and two classes that inherit from that class. However, it is telling me that one child is an instanceof the other child… that can’t be correct, can it? What am i doing wrong here?
function BaseClass(){}
function Child1(){}
Child1.prototype = BaseClass.prototype;
Child1.prototype.constructor = Child1;
function Child2(){}
Child2.prototype = BaseClass.prototype;
Child2.prototype.constructor = Child2;
console.log((new Child1() instanceof Child2)); // true
Child1.prototype = BaseClass.prototype;Should be
Child1.prototype = Object.create(BaseClass.prototype)You don’t want the prototype object to be the same, you want a new prototype object that inherits from
BaseClassLive Example
Disclaimer:
Object.createis ES5, use the ES5-shim for legacy platform support.To give you a more thorough example :
Visually:
var Base = { ... }here we simply create an object with methods and properties. We want to be able to create an instance of this object. So
Baseis a “class” and all it’s methods and properties can be accessed from the instances (includingconstructor).Base.constructor.prototype = Base;You need to link the “Constructor function” which is a function you can call with
newwhich will give you a new instance of the objectConstructorFunction.prototypetogether with the prototype object. This is basically a bit of glue you need to do manually because ES does not do this for you.If you forgot to do this then the constructor function (which is
X.constructor) doesn’t have a.prototypeproperty to make instances inherit from.var Child = Object.create(Base);Create a new object whose
[[Prototype]]isBase. This basically is the start of your prototype chainChild.x = ...Now we add properties to our child object which are the methods instances of Child will inherit. Basically we are creating a new prototype object to inherit from. All instances will share the methods and also share the methods up the prototype chain (including
Base).ChildFactory = Child.constructor;the
newkey word only works on constructor functions and not prototype objects so we need to basically say “switch our prototype object variable to the constructor function variable”Personally when building up “classes” I find the prototype objects really pleasant to handle directly and when creating instances I find the constructor functions pleasant to handle.
Now when we call
var c = new Child(41);It will call the constructor function we defined which will increment
things, then call the base constructor.Note at this point the prototype chain of c looks like