As already mentioned, do not use __proto__ . This is a non-standard property. (It is now standardized for JavaScript in browsers. Still don't use it.) But
Subclass.prototype = new Superclass();
also not a good method. What if Superclass expects parameters?
You have the best options.
ES2015 and above
class handles all this plumbing for you; full example:
class Superclass { constructor(superProperty) { this.superProperty = superProperty; } method() { console.log("Superclass method says: " + this.superProperty); } } class Subclass extends Superclass { constructor(superProperty, subProperty) { super(superProperty); this.subProperty = subProperty; } method() { super.method();
ES5 and earlier
Let Subclass.prototype inherit only from Superclass.prototype . This can be done, for example, using ES5 Object.create :
Subclass.prototype = Object.create(Superclass.prototype); Subclass.prototype.constructor = Subclass;
And then in Subclass you call Superclass with this , referencing the object so that it can initialize:
function Subclass() { Superclass.call(this);
Full example:
function Superclass(superProperty) { this.superProperty = superProperty; } Superclass.prototype.method = function() { console.log("Superclass method says: " + this.superProperty); }; function Subclass(superProperty, subProperty) { Superclass.call(this, superProperty); this.subProperty = subProperty; } Subclass.prototype = Object.create(Superclass.prototype); Subclass.prototype.constructor = Subclass; Subclass.prototype.method = function() { Superclass.prototype.method.call(this);
ES3 and earlier
ES3 doesn't have Object.create , but you can easily write a function that sets up a prototype for you in much the same way:
function objectCreate(proto) { var ctor = function() { }; ctor.prototype = proto; return new ctor; }
(Note: You can half-shim Object.create by creating one that takes only one argument, but the option with multiple arguments to Object.create cannot be Object.create , so it will give the other code on the page the wrong idea if it also uses Object.create .)
Then you do the same as our ES5 example:
Full example:
function objectCreate(proto) { var ctor = function() { }; ctor.prototype = proto; return new ctor; } function Superclass(superProperty) { this.superProperty = superProperty; } Superclass.prototype.method = function() { console.log("Superclass method says: " + this.superProperty); }; function Subclass(superProperty, subProperty) { Superclass.call(this, superProperty); this.subProperty = subProperty; } Subclass.prototype = objectCreate(Superclass.prototype); Subclass.prototype.constructor = Subclass; Subclass.prototype.method = function() { Superclass.prototype.method.call(this);
Felix Kling May 14 '12 at 9:29 a.m. 2012-05-14 09:29
source share