1

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();
5

2 Answers 2

1

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
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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();

4 Comments

bind is not needed here
Thank you for your explanation!
So, this means, that we really cannot use arrow functions inside object methods?
Depends on whose if you want to access this and whose this you want to access in that function. If there is no need to access this and arguments then there is no reason not to use arrow function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.