A cached version of Crockford’s Object.create, up to ten times faster

2 comments

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.

Add a comment

2 comments