Ivan Kuckir
Ivan Kuckir

Reputation: 2549

JavaScript inherit object values

is it possible to inherit an Object (reference) value from a class?

function A()
{
    this.x = {};
}

function B()
{
    this.y = {};
}
B.prototype = new A();
//...
var b1 = new B();
var b2 = new B();
alert(b1.x == b2.x);    // true
alert(b1.y == b2.y);    // false

but I want both to be false... B.x should be different for each instance of B.

Upvotes: 2

Views: 391

Answers (2)

Chad
Chad

Reputation: 19609

Edit Bjorn Tipling's solution is the proper way to do this.


Try recreating the prototype when a new B is created:

function A()
{
    this.x = {};
}

function B()
{
    //c is recreated each time with a new
    //prototype to screw with.
    var c = function() {
        this.y = {};
    };
    //instead of assigning 1 single instance of "A" to
    //B's prototype. We a assign a new "A" instance each time
    //a B is created. Therefore each instance of B has its
    //own A instance in its prototype.
    c.prototype = new A();

    return new c;
}
//...
var b1 = new B();
var b2 = new B();
alert(b1.x == b2.x);    // false
alert(b1.y == b2.y);    // false

jsFiddle

Upvotes: 1

Bjorn
Bjorn

Reputation: 71830

Call A's constructor from B:

function B() {
  A.apply(this);
  this.y = {};
}
B.prototype = new A()

Imagine it as if it were a call to super in Java. That is in fact how it works in Closure Library and some other JavaScript frameworks.

var b1 = new B();
var b2 = new B();
alert(b1.x === b2.x); //false

Upvotes: 4

Related Questions