Search code examples
javascriptobjectinheritanceobject-create

JavaScript inheritance with Object.create()?


How do I inherit with the Object.create()? I tried these, but none are working:

var B = function() {};
var A = function() {};
A = Object.create(B);
A.prototype.C = function() {};

and

var B = function() {};
var A = function() {};
A.prototype.C = function() {};
A = Object.create(B);

and

var B = function() {};
A = Object.create(B);
var A = function() {};
A.prototype.C = function() {};

Nothing worked. How am I supposed to use this new Object.create()-function?


Solution

  • Object.create() is used to inherit objects, not constructors like you're trying to do. It pretty much creates a new object with the old object set as its prototypal parent.

    var A = function() { };
    A.prototype.x = 10;
    A.prototype.say = function() { alert(this.x) };
    
    var a = new A();
    a.say(); //alerts 10
    
    var b = Object.create(a);
    b.say(); //alerts 10
    b.x = 'hello';
    b.say(); //alerts 'hello'
    

    And just to make sure b is not just a clone of a,

    a.x = 'goodbye';
    delete b.x;
    b.say(); //alerts 'goodbye'