JavaScript inheritance: Object.create vs new

In your question you have mentioned that Both examples seem to do the same thing, It’s not true at all, because

Your first example

function SomeBaseClass(){...}
SomeBaseClass.prototype = {
    doThis : function(){...},
    doThat : function(){...}
}
function MyClass(){...}
MyClass.prototype = Object.create(SomeBaseClass.prototype);

In this example, you are just inheriting SomeBaseClass' prototype but what if you have a property in your SomeBaseClass like

function SomeBaseClass(){ 
    this.publicProperty='SomeValue'; 
}

and if you use it like

var obj=new MyClass();
console.log(obj.publicProperty); // undefined
​console.log(obj);​

The obj object won’t have publicProperty property like in this example.

Your second example

MyClass.prototype = new SomeBaseClass();

It’s executing the constructor function, making an instance of SomeBaseClass and inheriting the whole SomeBaseClass object. So, if you use

    var obj=new MyClass();
    console.log(obj.publicProperty); // SomeValue
    console.log(obj);​

In this case its publicProperty property is also available to the obj object like in this example.

Since the Object.create is not available in some old browsers, in that case you can use

if(!Object.create)
{
    Object.create=function(o){
        function F(){}
        F.prototype=o;
        return new F();
    }
}

Above code just adds Object.create function if it’s not available so you can use Object.create function and I think the code above describes what Object.create actually does. Hope it’ll help in some way.

Leave a Comment