Inheritance in JavaScript – A Cool Way
First of all we will define a helper method used to copy the properties from one object to another, overriding the common ones:
function ex (destination, source) {
var p;
for (p in source) {
if (source.hasOwnProperty(p)) {
destination[p] = source[p];
}
}
return destination;
}
Let’s define our main extending method:
function extend (data, staticData) {
var parent = this,
child = function () {
if (data.initialize) {
data.initialize.apply(this, arguments);
} else {
parent.apply(this, arguments);
}
};
ex(child, parent);
if (staticData) {
ex(child, staticData);
}
if (!data) {
data = {};
}
child.prototype = ex(Object.create(parent.prototype), data);
child.prototype.constructor = child;
child.prototype.__super = parent.prototype;
return child;
}
The idea is that this method is called on the class to become parent class.
It has two parameters – data and staticData.
The data parameter is used to pass instance fields and methods to the child class that may override parent ones.
The staticData is used to define class level fields and methods to the child class.
Let’s use it!
function Foo (a, b) {
this.a = a;
this.b = b;
}
Foo.prototype.c = function () {
return this.a + this.b
};
var foo = new Foo(2, 5);
console.log(foo.c());// 2+7
Now is time for the inheritance!
Foo.extend = extend;
Bar = Foo.extend({
initialize: function (a, b, d) {
this.__super.constructor(a, b);
this.d = d;
},
d: 8,
e: function () {
return this.a + this.b + this.d;
}
});
var bar = new Bar(3, 1, 9);
console.log(bar.c(), bar.e()); // 3+1=4, 3+1+9=13
Written by meddle
Related protips
2 Responses
Try prototypal inheritance with stamps. http://ericleads.com/2014/02/prototypal-inheritance-with-stamps/
Seems too complex to me :)
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside