Nicc
Nicc

Reputation: 777

add a method to a prototype

I have the following code

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();

I'd like to add a method to manUtils() which will be only available to man, not to human and woman, such as i can call man.foo().

How can i make the constructor man() to point to manUtils and still accessing humanUtils functions so that i can call adam.sayRace() and adam.foo() inherited from manUtils ?

i don't want to use the new es6 class neither the traditional prototype reassignment (mdn)...if it is possible

Upvotes: 2

Views: 121

Answers (1)

Damiaan Dufaux
Damiaan Dufaux

Reputation: 4805

Is there a reason for not putting the race property in the humanUtils? If not, just put the race there and you can make the constructor man() to point to manUtils and still access humanUtils' functions by writing

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

And then, if you want to add a method to manUtils, simply write manUtils.fancyNewMethod = yourNewMethod

A note on new

In your example it makes no sense to use the new operator to construct mankind, adam and eve. When you write new human, a new object is created (lets call it A for reference) with as prototype human.prototype (which is an empty object, since you don't want to reassign humanUtils to human.prototype) and then human is executed with this bound to A. But inside your human constructor you discard A and instead create your own object using Object.create(humanUtils).

Full example

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()

Upvotes: 1

Related Questions