【问题标题】:JavaScript inherit object valuesJavaScript 继承对象值
【发布时间】:2012-01-31 13:52:51
【问题描述】:

是否可以从类中继承对象(引用)值?

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.x 对于每个 B 实例应该是不同的。

【问题讨论】:

  • 但是只有一个A;如果你想要不同的 A,那么将单个 A 作为原型是行不通的。

标签: javascript object superclass inheritance


【解决方案1】:

从 B 调用 A 的构造函数:

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

把它想象成 Java 中对 super 的调用。事实上,这就是它在 Closure 库和其他一些 JavaScript 框架中的工作方式。

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

【讨论】:

  • 那是因为您忘记在 jsfiddle 中添加 y。它为 b1.x === b2.x 返回 false,这是他要求的。
  • 在您的原始帖子中,没有 y; +1 以获得更简单的解决方案。
  • 因为这不是问题所在。在您的 jsfiddle 中,它返回 true 一次,因为它正在比较两个未定义的!
【解决方案2】:

编辑 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

【讨论】:

  • 我不知道你可以从你用 new 调用的函数返回。 Man JavaScript 有时会惹恼我。
  • 抱歉,这是个愚蠢的想法 - 没有删除 cmets :-)
猜你喜欢
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-12
相关资源
最近更新 更多