首页 > 解决方案 > 向原型添加方法

问题描述

我有以下代码

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)......如果可能的话

标签: javascriptoop

解决方案


有没有理由race财产放在里面humanUtils?如果没有,只需将比赛放在那里,您就可以通过编写使构造函数man()指向manUtils并仍然访问 humanUtils 的函数

function man() {
  return Object.create(manUtils)
}

然后,如果要向 中添加方法manUtils,只需编写manUtils.fancyNewMethod = yourNewMethod

关于new

在您的示例中,使用new运算符来构造人类亚当和夏娃是没有意义的。当您编写时new human,将创建一个新对象(让我们调用它A以供参考)作为原型human.prototype(这是一个空对象,因为您不想重新分配humanUtilshuman.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()


推荐阅读