1

I realise this is a pointless thing to do but I don't understand why it doesn't work.

var person = {
    _name: "Steve",
    doSomething: () => console.debug("Doing stuff with ", this._name)
}

"this" is bound to the global object and not the object getName was invoked on. I was expecting that the above is equivalent to :

var person = {
    _name: "Steve",
    doSomething: function() { console.debug("Doing stuff with ", this._name) }
}

(I know you should write it like this)

var person = {
   _name: "Steve",
   doSomething() {
      console.debug("Doing stuff with ", this._name)
   }
}
6
  • 2
    "I know you should write it like this" - No, you should not. Commented Oct 23, 2014 at 11:47
  • Strange: In Chrome Version 38.0.2125.104 (64-bit), this still refers the window object. Commented Oct 23, 2014 at 12:00
  • @thefourtheye sure you're calling it like person.getName()? Commented Oct 23, 2014 at 12:00
  • @thefourtheye I cannot think why you say you should not use that style - perhaps I confused the issue by using a get function, suppose the function does something other that simply return a value. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Oct 23, 2014 at 12:08
  • 1
    And I guess, the equivalent would rather be function() { return console.debug("Doing stuff with ", this._name) } Commented Dec 18, 2014 at 11:35

1 Answer 1

1

From mdn:

Arrow functions capture the this value of the enclosing context

This is different to functions.

Sign up to request clarification or add additional context in comments.

3 Comments

@RahilWazir Oh, I didn't see the class, I thought that it is a function.
@Woody Hmm I thought that part got nuked from ES6, it was probably something else, I've removed that part from my answer.

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.