-1

This is just a bit of a nonsense example but it perfectly describes my problem.

The following call of the object's function gives undefined for bird property:

const birds = {
 species:['Grey tinamou','Greater rhea','Dwarf cassowary'],
 bird: 'Bird',
 summary: function(){
  return this.species.map(function(species) {
   return `${species} is a ${this.bird}`;
  });
 }
};

birds.summary();

1) How can I access the bird property in the object's function?

2.1) Can I do this without passing in the bird property's value itself?

Like this: birds.summary(birds.bird);

2.2) is there a better/another way to do that?

1 Answers1

0

In a regular function, this is the object from which the function is called. If you call birds.func(), then inside this function this === birds. If the function is called just like func(), then the context will be window (undefined in strict mode). In the callback function that you passed to map, this is window or undefined. The arrow function works differently - it inherits this from the context where it is declared.

Use () => {} for inherit this from function summary:

this.species.map((species) => {...

And read about this.

Michael Mishin
  • 586
  • 2
  • 8
  • Thank you for your answer! Sorry for bothering but will the article help me to answer the question - why the `bird` property is accessible inside of an arrow function and not with a regular function? – Vitaly Platonov Jun 04 '20 at 10:17
  • I know the Russian language if that's what you are asking. – Vitaly Platonov Jun 04 '20 at 10:20
  • @VitalyPlatonov Да, в этой статье есть вся необходимая информация, но если коротко, то в обычной функции `this` - объект, от которого вызвана функция. То есть если вы вызываете birds.func(), то внутри этой функции `this === birds`. Если функция вызвана просто как func(), то контекстом будет window (или другое, в зависимости откуда вызвана функция). В функции коллбэка, которую вы передали в map, `this` равен `undefined`. Стрелочная функция работает иначе - она наследует this из того контекста, где она объявлена. – Michael Mishin Jun 04 '20 at 10:23
  • чуть наврал, в коллбэке this будет равен window, если не включен strict mode – Michael Mishin Jun 04 '20 at 10:29
  • thank you for your detailed answer! I'll go through the article and edit your answer a bit later so other people can benefit from this (link to the article may get broken). If you do that ahead of me - let me know I will mark it as accepted then, thanks. – Vitaly Platonov Jun 04 '20 at 10:29