简体   繁体   中英

Javascript - why is this referring to global window if I pass an arrow function as callback vs defined same func inside the callback handler?

Why is the value of this in first example: this: myObject and document/window in the second example? If this is defined/evaluated when the function is called, then I dont understand it.

myObject = {
  myMethod: function () {
    helperObject.doSomethingAsync('superCool', () => {
      console.log(this); // this === myObject
    });
  },
};
const reusabledCallback = () => {
  console.log(this); // this === window or global object
};

myObject = {
  myMethod: function () {
    helperObject.doSomethingAsync('superCool', reusabledCallback);
  },
};
  • this in an arrow function is the same this as the one in the outer scope where the function is defined.
  • this in a function declared with the keyword function is the object on which the function is being called.
  • this in the global scope is the window object (or the relevant global object)

In your first code, the arrow function containing this is defined inside a function , so this is whatever called that function ( myObject in your case).

In your second code, the arrow function containing this is defined in the global scope, so this is the global object ( window ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM