var std_obj = {
activeEffect : 'fade',
name : 'Jane',
displayMe() {
const doSomeEffects = () => {
if (this.activeEffect === 'fade') {
console.log(this.name); // this.name have accesss and logs
// return this.name --> gives undefined ? why can't I return?
}
};
doSomeEffects();
}
};
console.log(std_obj.displayMe());
// console.log(this.name) works but I cannot return this.name and I'm a bit frustrated
Arrow functions will take the this of their declaration scope. That is why the this here will point to the object. But to see that value you will have to change your code like this:
var std_obj = {
activeEffect : 'fade',
name : 'Jane',
displayMe() {
const doSomeEffects = () => {
if (this.activeEffect === 'fade') {
console.log(this.name); // this.name have accesss and logs
return this.name; //uncomment this
}
};
return doSomeEffects(); //if you do not use return statement, then it will by default return undefined
}
};
console.log(std_obj.displayMe());
If you will not return anything from displayMe() or doSomeEffects() it will not show undefined. The reason is functions by default return undefined. To test this : just run console.log("hello"); in dev console. This will show hello and undefined.
Note: If you use function expression instead of arrow functions, it will return undefined. That is the power of arrow functions.
You're not returning from displayMe, you're returning from doSomeEffects. The final line of displayMe is doSomeEffects(), with no return value. You need return doSomeEffects().
displayMe() {
const doSomeEffects = () => {
if (this.activeEffect === 'fade') {
console.log(this.name); // this.name have accesss and logs
return this.name // return from `doSomeEffect`
}
};
return doSomeEffects(); // return from `displayMe`
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With