Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this does not return object property (arrow, 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 --> 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

like image 506
emre-ozgun Avatar asked May 14 '26 22:05

emre-ozgun


2 Answers

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.

like image 73
Tushar Shahi Avatar answered May 16 '26 13:05

Tushar Shahi


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`
  }
like image 20
meagar Avatar answered May 16 '26 12:05

meagar