0

I am trying to make a function and later attach it to an existing object. these are my objects:

const cake1 = new Obj('cake1','cake','vanilla');
const cake2 = new Obj('cake2','cake','chocolate');
const cake3 = new Obj('cake3','cake','vanilla');

Right now they don't have any methods.

These are my functions and data:

const flavors = ['vanilla','chocolate'];
const isChocolate = (cake , flavors) => {
  console.log(cake);
    if(typeof cake === 'object' && typeof cake.type !== 'undefined' && cake.type === 'cake'){
      if(typeof cake.meta !== 'undefined'){
         if(cake.meta === flavors[1]){//Chocolate
           return true;
         }
      }
    }
    return false;//Any other case
}

const checkTheCake =(flavors,isChocolate) => {
  if(isChocolate( this , flavors)) {  // this refer to window
    console.log('is chocolate');
  }else{
    console.log('is vanilla');
  }
}

And at last, I added the checkTheCake function as a method.

cake1.checkTheCake = checkTheCake;
cake2.checkTheCake = checkTheCake;
cake3.checkTheCake = checkTheCake;

cake1.checkTheCake(flavors, isChocolate);
cake2.checkTheCake(flavors, isChocolate);
cake3.checkTheCake(flavors, isChocolate);

At first when I ran that code this within checkTheCake referred to the window object. And when I changed checkTheCake from expression to statement I managed to solve the problem and it referred to my cake object.

function checkTheCake (flavors,isChocolate){
  if(isChocolate( this , flavors)){ //this refers to cake
    console.log('is chocolate');
  }else{
    console.log('is vanilla');
  }
}

My question is why javascript behave like this in that particular case.

After edit: at first, I thought the problem is about the function statement and function expression but it actually relates to the Arrow function.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Zohar Revivo
  • 485
  • 1
  • 7
  • 18
  • 1
    The issue isn't whether you used a function expression or not. It about whether your function expression uses an arrow function. (A simple comment like this upon closing a question as a duplicate can go a long way toward helping users understand what's going on.) – Cat Mar 09 '19 at 21:32
  • yes, now I see that `const checkTheCake = function(flavors,isChocolate)`act the same way and it is about the arrow function indeed. – Zohar Revivo Mar 09 '19 at 21:37

0 Answers0