Background
After reading the below few posts about this
variable in JavaScript. I think I have to write a post to note down my understanding about it.
http://www.ruanyifeng.com/blog/2010/04/using_this_keyword_in_javascript.html
https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000
Function call
In the normal function call, this
is the global variable, which is window
when the page is loaded in web browser. test()
is the same as window.test()
.
1 | var x = 1; |
Method call
When the function is used as a method of an object, this
is reference to the object
when the method (function) is called.
1 | var x = 1; |
Constructor function
When the function is used as a constructor function, this
is reference to the object
in the construction function.
1 | var x = 1; |
Method apply
Developer can use the method object.apply
to change the binding of this
.
1 | var x = 1; |
Function call in method call
If this
variable is used in a function call in an object method call, it will be the reference to window
, instead of the reference to the object
.
1 | var x = 1; |
To set this
to the reference to the object
in the above case, you can use a variable like that
to store this
variable as below.
1 | var x = 1; |