JavaScript继承对象值

时间:2012-01-02 01:31:20

标签: javascript object superclass inheritance

是否可以从类继承Object(reference)值?

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

但我希望两者都是假的......对于B的每个实例,B.x应该是不同的。

2 个答案:

答案 0 :(得分:4)

从B调用A的构造函数:

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

想象一下,就像是在Java中调用super一样。事实上,它在Closure Library和其他一些JavaScript框架中是如何工作的。

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

答案 1 :(得分:1)

编辑 Bjorn Tipling的解决方案是正确的方法。


尝试在创建新B时重新创建原型:

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