Search code examples
javascriptobjectreturnthisarrow-functions

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


Solution

  • 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.