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.