我有两节课。我想从实例访问Parent的type
属性:
// Parent class
function Animal() { this.type = 'animal' }
// Child class
function Rabbit(name) { this.name = name }
// I inherit from Animal
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit; // I want to keep Rabbit constructor too
// I instantiate my Rabbit and am trying to access rabbit.type
const rabbit = new Rabbit('Bunny');
rabbit.name // => Bunny
rabbit.type // => undefined. WHY?
我知道如何解决它并访问type
,但......
// all is the same
// Child class
function Rabbit(name) {
Animal.apply(this, arguments); // Just need to add this line in Rabbit class
this.name = name
}
// all is the same
rabbit.name // => Bunny
rabbit.type // => animal
...但为什么它在第一个例子中不起作用?是否有可能在不使用Animal.apply
的情况下实现它?
是的,如果你要将type
添加到原型中:
Animal.prototype.type = "animal";
或者你可以隐藏在Animal.apply
糖背后的class
电话:
class Animal {
constructor() {
this.type = "animal";
}
}
class Rabbit {
constructor(name) {
super(); // <<<
this.name = name;
}
}
Rabbit.prototype = Object.create(Animal.prototype);
只扩展了prototype
链中定义的属性。构造函数中定义的属性不会被扩展。
试试这个,
...
Rabbit.prototype = new Animal();
...
更新示例:
// Parent class
function Animal() { this.type = 'animal' }
// Child class
function Rabbit(name) { this.name = name }
Rabbit.prototype = new Animal();
Rabbit.prototype.constructor = Rabbit;
const rabbit = new Rabbit('Bunny');
console.log(rabbit.name);
console.log(rabbit.type);