简体   繁体   中英

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... Bx should be different for each instance of B.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM