javascript - 向原型添加方法
问题描述
我有以下代码
const humanUtils = {
sayRace: function(){
console.log('Im a '+ this.race);
}
}
function human() {
const human = Object.create(humanUtils);
human.race = 'human';
return human;
}
const manUtils = Object.create(humanUtils);
function man() {
const createMan = new human();
createMan.gender = 'man';
return createMan
}
function woman() {
const createWoman = new human();
createWoman.gender = 'woman';
return createWoman;
}
const mankind = new human();
const adam = new man();
const eve = new woman();
我想向 manUtils() 添加一个方法,该方法仅对男人可用,对人类和女人不可用,例如我可以调用 man.foo()。
如何使构造函数 man() 指向 manUtils 并仍然访问 humanUtils 函数,以便我可以调用adam.sayRace()
并adam.foo()
从 manUtils 继承?
我不想使用新的 es6 类,也不想使用传统的原型重新分配(mdn)......如果可能的话
解决方案
有没有理由不把race
财产放在里面humanUtils
?如果没有,只需将比赛放在那里,您就可以通过编写使构造函数man()
指向manUtils
并仍然访问 humanUtils 的函数
function man() {
return Object.create(manUtils)
}
然后,如果要向 中添加方法manUtils
,只需编写manUtils.fancyNewMethod = yourNewMethod
关于new
在您的示例中,使用new
运算符来构造人类亚当和夏娃是没有意义的。当您编写时new human
,将创建一个新对象(让我们调用它A
以供参考)作为原型human.prototype
(这是一个空对象,因为您不想重新分配humanUtils
给human.prototype
),然后human
使用this
绑定到执行A
。但是在您的human
构造函数中,您丢弃A
并使用创建自己的对象Object.create(humanUtils)
。
完整示例
const humanUtils = {
sayRace() {
console.log('Im a '+ this.race);
},
race: 'human'
}
function human() {
return Object.create(humanUtils);
}
const manUtils = Object.create(humanUtils, {
gender: { value: 'man' }
});
function man() {
return Object.create(manUtils)
}
function woman() {
const createWoman = new human();
createWoman.gender = 'woman';
return createWoman;
}
const mankind = human();
const adam = man();
const eve = woman();
console.log(adam.gender)
adam.sayRace()
console.log('humanUtils isPrototypeOf adam:', humanUtils.isPrototypeOf(adam))
console.log('manUtils isPrototypeOf eve:', manUtils.isPrototypeOf(eve))
manUtils.saySlogan = function() {console.log('men are cool because they have a slogan')}
adam.saySlogan()
推荐阅读
- android - 为什么尽管有 -dontwarn 和 -keep 类,ProGuard 仍然会发出警告?
- go - Golang 接口上的指针接收器和值接收器
- c# - ControlTemplate 中的 UWP TemplateBinding 到固定值
- html - 在 Vue js -> v-model 我如何集成 vlaue?
- r - 当序列包含间隙时如何计算序列之间的差异?
- python - 删除包含特定键的列表下的所有字典
- php - 相同的代码仅适用于我使用的 2 台服务器中的 1 台
- json - 根据键值的否定创建 Json 模式依赖项
- javascript - React:根据登录状态有条件地在路由中渲染组件,而不显示加载页面
- wpf - menuitem.icon 中的 wpf 可变图像