0

here are two simple codes:

let myObject = {
objectName: () => {
    console.log(this);
}
};

myObject.objectName(); 

First code print "this" value as: { }

let myObject = {
objectName: function() {
    console.log(this);
}
};

myObject.objectName();

Second code print "this" value as: { objectName: [Function: objectName] }

Can somebody explain in plain English why "this" in arrow function has different value ? Thank you!

zorro
  • 1,045
  • 1
  • 5
  • 11
  • 1
    because, well ... [here's some documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) – Jaromanda X May 08 '18 at 12:20
  • Arrow functions adopt the *this* of their enclosing scope. – RobG May 08 '18 at 12:21

1 Answers1

0

An arrow function expression has a shorter syntax than a function expression and does not have its own this , arguments, super, or new.target. The this value of the enclosing execution context is used.

If you don't use an arrow function, a function gets its this value from where it is called.

Check this for more details

How does event handlers with arrow functions achieve context binding

Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318