sách gpt4 ai đã đi

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

In lại 作者:行者123 更新时间:2023-12-01 02:59:41 25 4
mua khóa gpt4 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);

通过经典继承,我可以使用 trường hợp của 来了解给定对象在其链中是否具有给定的 proto (例如 musician instanceof Human >)。

Đây làproto链的样子,它看起来与使用mới运算符创建的链非常相似。

nhập mô tả hình ảnh ở đây

câu hỏi如何通过原型(prototype)继承实现同样的效果?

1 Câu trả lời

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

  • trường hợp của 的 RHS 必须是一个函数,因此您的类型必须构建在函数之上。
  • 您没有区分静态/类型方法和实例方法。 tạo nên 是一种类型方法。 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/

25 4 0
Bài viết được đề xuất: pdf - Jasperreports 标记属性和 PDF
Bài viết được đề xuất: Ngoại lệ Jquery blur()
Bài viết được đề xuất: python - gensim 文件未找到错误
Bài viết được đề xuất: c# - 在Web方法中创建cookie
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com