Javascript: using inheritance "as is"
I want to use very simple inheritance in Javascript without any libraries (jQuery, Prototype, etc.) and I forget how to do it.
I know how to create a simple non-inherited object:
function Foo(x)
{
this.x = x;
}
Foo.prototype = {
inc: function() { return this.x++; }
}
which I can use like this:
js>f1=new Foo(0)
[object Object]
js>f1.inc()
0
js>f1.inc()
1
js>f1.inc()
2
But how would you add a subclass with one additional method that inherits the Foo "inc" method without changing the Foo class?
function Bar(x)
{
this.x = x;
}
Bar.prototype = new Foo();
Bar.prototype.pow = function(y) { return this.x+"^"+y+"="+Math.pow(this.x,y); }
This seems to be correct, except for this constructor oddity; I need to call the Foo constructor once to prototype Bar, and when Bar's constructor is called there seems to be no way to call Foo's constructor.
Any suggestions?
source to share
The trick is to use Object.create instead of execution new Foo()
. It will also create a new object that inherits Foo.prototype, but without calling the Foo constructor.
Bar.prototype = Object.create(Foo.prototype);
Although Object.create cannot be defined in older browsers, you can define it yourself if you need to. (following code from MDN link)
if (!Object.create) {
Object.create = function (o) {
if (arguments.length > 1) {
throw new Error('Object.create implementation only accepts the first parameter.');
//tbh, the second parameter is for stuff you dont need right now.
}
function F() {}
F.prototype = o;
return new F();
};
}
source to share
You can use this code. It does exactly what you do, which is the only way I know of for inheritance, but this function uses create
which is new in ECMAScritp 5 if available, and does some additional checking:
function inherit(p) {
if (p == null) throw TypeError(); // p must be non-null
if (Object.create) // If Object.create() is defined (ECMAScript 5 way)
return Object.create(p); // use it
var t = typeof p; // If not, do some more checking (the old way)
if (t !== "object" && t !== "function") throw TypeError();
function f() {}; // Define constructor
f.prototype = p; // Set prototype to p.
return new f(); // call constructor f() to create an "heir" of p
}
source to share