JSFiddle - React, Tailwind, and code Playground
by Khalil Zhang
JavaScript
// the parent constructor
function Parent(name) {
this.name = name || 'starandtina';
}
// adding functionality to the prototype
Parent.prototype.say = function () {
return this.name;
};
// empty child constructor
function Child(name) {}
// inheritance magic happens here
inherit(Child, Parent);
// #1
function inherit(C, P) {
C.prototype = new P();
}
// #2
function Child(a, c, b, d) {
Parent.apply(this, arguments);
}
Child.prototype = new Parent();
// #3
function inherit(C, P) {
C.prototype = P.prototype;
}
// #4
function inherit(C, P) {
var F = function () {};
F.prototype = P.prototype;
C.prototype = new F();
C.uber = P.prototype;
C.prototype.constructor = C;
}
// #5
// avoid creating the temporary (proxy) constructor every time you need inheritance. It’s sufficient to create it once and only change its prototype. You can use an immediate function and store the proxy function in its closure:
var inherit = (function () {
var F = function () {};
return function (C, P) {
F.prototype = P.prototype;
C.prototype = new F();
C.uber = P.prototype;
C.prototype.constructor = C;
}
}());
var kid = new Child();
alert(kid.say()); // "starandtina"