function A(){
// sort of like this
// this.arr = [];
}
function B(){
// not here though
// this.arr = [];
}
B.prototype = new A(); // all B instances would share this prototypes attributes
// I want all B instances to have an arr attributes (array)
// of their own but I want the parent class to define it
var b1 = new B();
var b2 = new B();
b1.arr.push(1);
b2.arr.push(2);
b1.arr.length === 1; // should be true
b2.arr.length === 1; // should be true
我想在 A
中编写代码,为子类 B
的每个实例定义一个 arr
变量,这样 arr
是每个 B
实例的新对象。我可以通过在 B
构造函数中设置 this.arr = []
来实现这一点,但这是否可以通过将代码写入 A
来实现相反?
最佳答案
你在Javascript中继承的想法有很大问题。在 javascript 中,你真的有对象,仅此而已。构造函数是一种使用 new
调用并创建新对象的方法。
这部分代码并不是真正的正确
,因为您正在使用从 A 创建的对象创建原型(prototype)...也就是说,您实际上并没有使用原型(prototype) A
。正如所说的继承并不真正存在,你必须实现一些东西来调用创建对象 B
所需的每个构造函数。
B.prototype = new A();
你应该改用这个方法:
B.prototype = Object.create(A.prototype)
在这种情况下,您将在 B 中拥有 A 的所有原型(prototype)...但是如果有必要,您仍然必须调用 A
的构造函数。
function A() {
this.arr = []
}
function B() {
A.call(this)
}
使用更复杂的库,你可能会得到继承和类似于 python 中的 super
的东西。如果您真的很感兴趣,您还可以创建一个结构,该结构将自动调用每个子原型(prototype)的每个构造函数。
关于Javascript 继承实例属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30330221/