Key words: arrow function, scope

The problem

In global scope, this points to window when the arrow function is an object method:

  var name = "Bob";
  obj = {
    name: "John".sayHello: () = > {
      console.log( this.name); }}; obj.sayHello();// Bob instead of John
Copy the code

The premise

To solve this problem, you need to know two premises.

  1. This of the arrow function points to this of the scope of the arrow function itself
  var fruits= ["watermelon"."mango"];
  obj = {
    likes: {
      fruits: ["apple"."banana"].getLikes() {
        console.log(this); // This in this case means likes
        let getFruits = () = > {
          // The arrow functions are in the body of getLikes,
          // So this is also likes here
          console.log(this.fruits); }; getFruits(); ,}}}; obj.likes.getLikes();// ["apple", "banana"]
Copy the code
  1. The function scope chain is determined when the function is declared, as follows:
 var a = 10;
 function foo() {
   console.log(a);
 }
 function bar() {
   var a = 20;
   foo();
 }
 bar(); // 10 instead of 20
Copy the code

explain

Premise 1 above explains the problem at the beginning of this article (see code comments)

  var name = "Bob";
  obj = {
    name: "John".sayHello: () = > {
      // arrow functions are declared in global scope,
      // So this represents window(undefined in strict mode).
      console.log(this.name); }}; obj.sayHello();// Bob instead of John
  
  // call sayHello outside obj
  function foo() {
    obj.sayHello();
  }
  foo(); // Also Bob, not John
Copy the code