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 @   saaspeter  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示