2

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.

1
  • 1
    But there's only one A; if you want different As, having a single A as a prototype won't work. Commented Jan 2, 2012 at 1:33

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

That's because you forgot to add the y in your jsfiddle. It returns false for b1.x === b2.x which is what he asked for.
In your original post, there was no y; +1 for a simpler solution.
Because that wasn't the question. In your jsfiddle it returns true once because it's comparing two undefined!
1

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

2 Comments

I didn't know you could return from a function you're calling with new. Man JavaScript bugs me sometimes.
sorry, has been a dumb idea - no deletion of comments :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.