this does not return object property (arrow, this)

Viewed 65
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

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

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`
  }

I'm not sure but I think

var std_obj = {
  activeEffect : 'fade',
  name : 'Jane',
  displayMe() {
    const doSomeEffects = () => {
      if (this.activeEffect === 'fade') { 
        console.log(this.name);
        return this.name
      }
    };
    return doSomeEffects();
  }
};
console.log(std_obj.displayMe());

this is what you're trying to do

doSomeEffects inside displayMe returns this.name and you're calling displayMe

am I right?

Related