gpt4 book ai didi

JavaScript - 使用 B.prototype=new A() 继承数组

转载 作者:搜寻专家 更新时间:2023-11-01 04:26:40 24 4
gpt4 key购买 nike

(我是 JavaScript 新手)。以下代码:

function A() {
console.log('Constructing A');
this.a = new Array();
}
function B(x) {
console.log('Constructing B');
this.a.push(x);
this.b = x;
}
B.prototype = new A();
b1 = new B(10);
b2 = new B(11);
console.log('b1', b1);
console.log('b2', b2);​

导致 b1 和 b2 共享单个 this.a 数组(但不同 this.b)。这就像一个浅拷贝。

我不太明白什么是创建单独 this.a 数组的正确方法。我希望它们继承,因为这是代码的逻辑,此外我不想在每个子对象中创建它们(在我的例子中有很多子对象)。

最佳答案

我对这个问题的解释很感兴趣。我读过@Niko 的重复问题,但似乎这就是不同之处:

 function A() {
console.log('Constructing A');
this.a=new Array();
}

function B(x) {
console.log('Constructing B');
A.call(this); //--> calling the super() constructor creates a new array
this.a.push(x);
}

B.prototype = new A();

b1 = new B(11);
b2 = new B(12);
console.log(b1.a);
console.log(b2.a);

关于JavaScript - 使用 B.prototype=new A() 继承数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12129540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com