gpt4 book ai didi

javascript - 原型(prototype)继承: how to get instanceof?

转载 作者:行者123 更新时间:2023-12-01 02:59:41 24 4
gpt4 key购买 nike

看完这个video我了解了一种用 Javascript 实现继承的好方法:原​​型继承。此方法使用 Object.create/Object.assign 根据另一个实例创建一个新对象。这看起来非常有趣,因为很容易理解正在发生的事情。例如:

const human = {
species: 'human',
create: function(values) {
const instance = Object.create(this);
Object.assign(instance, values);
return instance;
},
sayName: function() {
console.log(`Hi, my name is ${this.name}`);
},
saySpecies: function() {
console.log(`Hi, I'm a ${this.species}`);
}
}

const musician = human.create({
species: 'musician',
playInstrument: function() {
console.log(`I'm a musician and I play ${this.instrument}`);
}
});

const aHuman = human.create({ name: 'Paul' });
aHuman.sayName();
aHuman.saySpecies();

const aMusician = musician.create({ name: 'David', instrument: 'Guitar' });
aMusician.sayName();
aMusician.saySpecies();
aMusician.playInstrument();

// how to check if musician is an instance of human?
console.log(musician instanceof human);

通过经典继承,我可以使用 instanceof 来了解给定对象在其链中是否具有给定的 proto (例如 musician instanceof Human >)。

这就是proto链的样子,它看起来与使用new运算符创建的链非常相似。

enter image description here

问题如何通过原型(prototype)继承实现同样的效果?

最佳答案

您的尝试存在两个主要问题:

  • instanceof 的 RHS 必须是一个函数,因此您的类型必须构建在函数之上。
  • 您没有区分静态/类型方法和实例方法。 create 是一种类型方法。 sayName 是一个实例方法。

以下内容应该按您的预期工作。

function Human(){}

Object.assign(Human, {
create: function(values) {
let newObj = Object.create(this.prototype);
return Object.assign(newObj, values);
}
});

Object.assign(Human.prototype, {
species: 'human',
sayName: function() {
console.log(`Hi, my name is ${this.name}`);
},
saySpecies: function() {
console.log(`Hi, I'm a ${this.species}`);
}
});

function Musician(){}

Object.assign(Musician, Human);

Musician.prototype = Human.create({
species: 'musician',
playInstrument: function() {
console.log(`I'm a musician and I play ${this.instrument}`);
}
});

const aHuman = Human.create({ name: 'Paul' });
aHuman.sayName();
aHuman.saySpecies();

const aMusician = Musician.create({ name: 'David', instrument: 'Guitar' });
aMusician.sayName();
aMusician.saySpecies();
aMusician.playInstrument();

// how to check if musician is an instance of human?
console.log(aMusician instanceof Human);

关于javascript - 原型(prototype)继承: how to get instanceof?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46520434/

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