A cached version of Crockford’s Object.create, up to ten times faster
Most Javascript programmers know Douglas Crockford’s famous prototypal inheritance utility, Object.create (written here as a global clone
function):
function clone(o) {
function F(){}
F.prototype = o;
return new F();
}
You can use this utility to do inheritance in Javascript ‘the right way’:
function Parent(name) {
this.name = name;
}
Parent.prototype = {
"getName" : function() {
return this.name;
}
}
function Child() {
Parent.apply(this, arguments);
}
Child.prototype = clone(Parent.prototype);
var child = new Child("John");
child.getName(); // 'John'
child instanceof Child; // true
child instanceof Parent; // true
The clone
function can be made even faster by caching the F
function:
var F = function(){};
function clone(o) {
F.prototype = o;
return new F();
}
Because the complete prototype
is overwritten you can use F
over and over again. Speed differences can be pretty big, according to a jsperf.com testcase i made. In IE8 the cached version is up to ten times faster.
Sándor Fekete
According to weird rewrited prototype behavior, maybe a fix would be necessary:
var F = function(){};
function clone(o) {
F.prototype = o;
F.prototype.constructor = F; // fix
return new F();
}
hay
@Sándor: with IE8 not being supported anymore, and all the other browsers having native support for Object.create, this shim becomes less and less useful really.