Getting an undefined in object method

Max Wolfen Source

Why I'm getting an undefined? So I think this is a problem inside the arrow functions... I need to amke it work by the arrow function inside the method say

const obj = {
                a: 42,
                say:  () => {
                    console.log(this.a);
                }
            };

            obj.say();
javascriptarrow-functions

Answers

answered 3 months ago gurvinder372 #1

Don't use arrow function, since they don't have their own this. So, this (in case of arrow functions) will point to enclosing context.

 var obj = {
      a: 42,
      say: function() { 
          console.log(this.a);
      }
 };

 obj.say();

answered 3 months ago Joseph Reeve #2

As other answers have explained, Arrow Functions don't have this values.

If you want similar concise syntax, you might want to try ES6 Method Definition syntax which does have this values, and is shorter than a whole function(){...}

var obj = {
  a: 42,
  say() {
    console.log(this.a);
  }
}

If you're structuring your app like this, it may make sense to go the whole hog and use ES6 Classes.

As a silly aside, it's also obviously possible that you can do the following:

var obj = {
  a: 42,
  say() {
    console.log(obj.a); //obj not this
  }
}

comments powered by Disqus