簡體   English   中英

JavaScript繼承對象值

[英]JavaScript inherit object values

是否可以從類繼承對象(引用)值?

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的每個實例Bx都應該不同。

從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

編輯 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM