The “this” Keyword
In JavaScript, as in most object-oriented programming languages, this is a special keyword that is used in methods to refer to the object on which a method is being invoked. The value of this is determined using a simple series of steps:
- If the function is invoked using
Function.callorFunction.apply, this will be set to the first argument passed tocall/apply. If the first argument passed tocall/applyis null or undefined,thiswill refer to the global object (which is thewindowobject in web browsers). - If the function being invoked was created using
Function.bind,thiswill be the first argument that was passed tobindat the time the function was created. - If the function is being invoked as a method of an object,
thiswill refer to that object. - Otherwise, the function is being invoked as a standalone function not attached to any object, and
thiswill refer to the global object.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
|
|
1
2
3
4
5
6
7
8
9
10
11
12
|
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
|
When invoking a function deep within a long namespace, it is often tempting to reduce the amount of code you need to type by storing a reference to the actual function as a single, shorter variable. It is important not to do this with instance methods as this will cause the value of this within the function to change, leading to incorrect code operation. For instance:
|
1
2
3
4
5
6
7
8
9
10
11
12
|
|
You can, however, safely reduce everything up to the object on which the method is invoked:
|
1
2
3
4
5
6
7
8
9
10
11
12
|
|