0

In this query, i've have small doubt i need to know WHY?

We are in #lockdown mean while one of my brother padu asked this question. Below i have sample object, in that there have functions while calling as directly its return 1 but while assign as const and access as function returns undefined. Someone have any explainations will real helpful to imporve my knowledge.

const apple = 3;
const data = {
  apple: 2,
  bag: {
    apple: 1,
    plastic: function(){
      return this.apple;
    }
  }
}
const plastic = data.bag.plastic;
console.log(plastic())             **//Result - undefined**
console.log(data.bag.plastic())    **//Result - 1**

Thanks,

Gopal.R

RGKrish183
  • 334
  • 3
  • 12

1 Answers1

0

You are searching for bind()

const apple = 3;
const data = {
  apple: 2,
  bag: {
    apple: 1,
    plastic: function(){
      return this.apple;
    }
  }
}
const plastic = data.bag.plastic.bind(data.bag);
console.log(plastic())           
console.log(data.bag.plastic())   
User863
  • 15,117
  • 2
  • 11
  • 33
  • Thanks for you information. answer for why? **plastic() has no calling context, so this does not refer to data.bag. And Solutions was yours.** https://www.codementor.io/@niladrisekhardutta/how-to-call-apply-and-bind-in-javascript-8i1jca6jp#bind-or-functionprototypebind – RGKrish183 Apr 04 '20 at 08:13