function inheritClass(Parent, child) {
function Child() {
var that = new (Parent.bind.apply(
Parent,
[].concat.apply([null], arguments)
))();
return (
child.constructor.apply(
Object.setPrototypeOf(that, Child.prototype),
arguments
) || that
);
}
Object.assign(Child, child.static);
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Object.assign(Child.prototype, child.prototype);
return Child;
}
function Parent(name) {
this.name = name;
}
Parent.prototype.speak = function () {
return "Hi, my name is " + this.name;
};
var Child = inheritClass(Parent, {
constructor: function (name, age) {
this.age = age;
},
prototype: {
speak: function () {
return [
Parent.prototype.speak.call(this),
"I'm " + this.age + " years old"
].join("\n");
}
}
});
var parent = new Parent("Donald"),
child = new Child("Ivanka", 38);
console.assert(child instanceof Child, "inherited from Child");
console.assert(child instanceof Parent, "inherited from Parent");
console.assert(
Parent.prototype.speak !== Child.prototype.speak,
"Parent's prototype is safe"
);
console.assert(child.constructor === Child, "Child's constructor is correct");
console.assert(
child.speak() === "Hi, my name is Ivanka\nI'm 38 years old",
"override Prototype methods"
);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.