我有两节课。我想从实例访问父项的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
来实现?
答案 0 :(得分:1)
是的,如果您要在原型中添加type
,
Animal.prototype.type = "animal";
或者您可以将Animal.apply
糖后面的class
调用隐藏起来:
class Animal {
constructor() {
this.type = "animal";
}
}
class Rabbit {
constructor(name) {
super(); // <<<
this.name = name;
}
}
答案 1 :(得分:1)
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);