我想知道为什么在这段代码中,当我试图访问构成 garfield
的对象的属性时,在本例中为 Cat
,我得到 undefined
:
function Cat(){
this.legs = 2;
this.species = 'cat';
};
Cat.prototype.makeSound = function() {
console.log(this.sound); // logs undefined
};
const garfield = Object.create(Cat);
garfield.sound = 'feed me';
garfield.makeSound();
console.log(garfield.legs) // logs undefined
难道我不能沿着原型(prototype)继承链访问这些属性吗?
最佳答案
OOP
一词在其定义中包含“对象”;这意味着您正在处理对象。
Javascript 做了一些特别的事情,它直接公开对象,您可以在其中使用它们而无需抽象(无需类)。
要创建对象,您只需使用 {}
声明即可。例如,无需创建一个类来获取 java
中的类。
要直接使用Inheritance,你需要有一个对象,并在它的原型(prototype)上追加一些东西。
这是一个例子:
const Cat = {
legs: 2,
species: 'cat',
};
Object.setPrototypeOf(Cat, {
makeSound() {
console.log(this.sound); // logs undefined
}
})
const garfield = Object.create(Cat);
garfield.sound = 'feed me';
garfield.makeSound();
console.log(garfield.legs) //2
要使用函数继承,您必须首先构造函数以从函数中获取对象(this
),原型(prototype)将自动附加到this
对象。
function Cat(){
this.legs = 2;
this.species = 'cat';
};
Cat.prototype.makeSound = function() {
console.log(this.sound); // logs undefined
};
const garfield = new Cat();
garfield.sound = 'feed me';
garfield.makeSound();
console.log(garfield.legs) // 2
关于javascript - Js - 具有对象创建功能的原型(prototype)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47486735/