【问题标题】:Javascript prototype undefined instead of inherited?Javascript原型未定义而不是继承?
【发布时间】:2016-08-19 01:57:15
【问题描述】:
function test() {
    this.a = {
        b: 4
    };
}

test.prototype.a = {
    c: 5
};

var example = new test();

为什么是example.a.c == undefined

难道不应该继承原型并返回5吗?


如果这不可能,有没有办法添加代码来返回原型?:

function test() {
    this.a = {
        b: 4,
        c: *this.return.prototype*
    };
}

【问题讨论】:

  • 您的原型适用于example.a.c,但this.a 优先于test.prototype.a
  • @Barmar 所以它不像 $.extend() 有 2 个对象创建一个新对象 a = {b: 4, c: 5};?
  • 没错,原型不是递归合并的。
  • 您可以为a.c 定义一个返回this.prototype.a.c 的getter。
  • @Barmar 这样的电话会是什么样子?

标签: javascript object prototype


【解决方案1】:

example.a 要么引用一个对象,要么引用另一个对象,你不能直接让它从不同对象中检索属性。

我要做的是让example.a 成为一个继承自另一个对象的对象:

function test() {
  this.a = Object.create(test.a_proto);
  this.a.b = 4;
}
test.a_proto = {
  c: 5
};
var example = new test();
console.log(example.a.b); // 4 (own)
console.log(example.a.c); // 5 (inherited)

【讨论】:

  • 如果他在创建example 后更改test.a_proto.c 会发生什么情况?它会继续使用继承的原型,还是在你调用Object.create(test.a_proto)时进行复制?
  • 我刚试了一下,它继续从proto继承。不错。
  • @Barmar 是的,test.a_proto 属性的更改将被继承。但是替换 test.a_proto 本身不会。
【解决方案2】:

a.c 定义一个访问原型的getter。

function test() {
  this.a = {
    b: 4,
    get c() {
      return test.prototype.a.c;
    }
  };
}

test.prototype.a = {
  c: 5
};

var example = new test();
console.log(example.a.b);
console.log(example.a.c);
// update prototype
test.prototype.a.c = 10;
console.log(example.a.c);

【讨论】:

    【解决方案3】:

    当你访问 'a' 时,它首先在 example 中找到。如果找不到,它会尝试在示例构造的原型中找到'a'。所以它会尝试访问test.ptototype.c。所以你的代码找不到examlpe.c。我想你可以这样改变你的代码。

    function test() {
        this.a = {
            b: 4
        };
    }
    test.prototype.c = 5;
    var example = new test();
    console.log(example.c);//print 5
    

    【讨论】:

    • 他想要example.a.c,而不是example.c
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多