this in Javascript

What is this?

In JavaScript, the this keyword refers to an object.

Which object depends on how this is being invoked (used or called).

The this keyword refers to different objects depending on how it is used:

In an object method, this refers to the object.
Alone, this refers to the global object.
In a function, this refers to the global object.
In a function, in strict mode, this is undefined.
In an event, this refers to the element that received the event.
Methods like call()apply(), and bind() can refer this to any object.

 

for the detail, see: https://www.w3schools.com/js/js_this.asp

also for bind method. see: https://www.javascripttutorial.net/javascript-bind/#:~:text=The%20bind%20%28%29%20method%20creates%20a%20new%20function%2C,This%20is%20known%20as%20function%20borrowing%20in%20JavaScript.

https://www.w3schools.com/js/js_function_bind.asp

当 this 和 arrow function在一起的时候,情况更加复杂了。但是记住这点:Arrow functions do not bind their own this, instead, they inherit the one from the parent scope, which is called "lexical scoping". 

see:https://www.codementor.io/@dariogarciamoya/understanding-this-in-javascript-with-arrow-functions-gcpjwfyuc 

https://www.codementor.io/@dariogarciamoya/understanding--this--in-javascript-du1084lyn 

关于this in arrow function, 也可以看这个解释:https://stackoverflow.com/questions/63541194/meaning-of-enclosing-lexical-context-when-we-use-arrow-function-lexical-this

 

posted @ 2023-05-27 17:09  saaspeter  阅读(6)  评论(0编辑  收藏  举报