gpt4 book ai didi

JavaScript:继承

转载 作者:行者123 更新时间:2023-11-30 13:24:26 29 4
gpt4 key购买 nike

我试图做继承,但没想到this.array会像静态成员一样。我怎样才能让它成为“ protected /公开的”:

function A() {
this.array = [];
}

function B() {
this.array.push(1);
}
B.prototype.constructor=B;
B.prototype = new A();

Firebug :

>>> b = new B();
A { array=[1]}
>>> b = new B();
A { array=[2]}
>>> b = new B()
A { array=[3]}

最佳答案

不是“私有(private)/ protected ”,但这将为每个 B 创建一个新数组。

function A() {
this.array = [];
}

function B() {
A.apply(this); // apply the A constructor to the new object
this.array.push(1);
}
// B.prototype.constructor=B; // pointless
B.prototype = new A();

关于JavaScript:继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9013301/

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