You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: page/javascript-101/this-keyword.md
+8-5Lines changed: 8 additions & 5 deletions
Original file line number
Diff line number
Diff line change
@@ -8,13 +8,14 @@ attribution:
8
8
9
9
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:
10
10
11
-
- If the function is invoked using `Function.call` or `Function.apply`, this will be set to the first argument passed to `.call()`/`.apply()`. If the first argument passed to `.call()`/`.apply()` is `null` or `undefined`, `this` will refer to the global object (which is the `window` object in web browsers).
12
-
- If the function being invoked was created using `Function.bind`, `this` will be the first argument that was passed to `.bind()` at the time the function was created.
11
+
- If the function is invoked using `Function.call()` or `Function.apply()`, this will be set to the first argument passed to `.call()`/`.apply()`. If the first argument passed to `.call()`/`.apply()` is `null` or `undefined`, `this` will refer to the global object (which is the `window` object in web browsers).
12
+
- If the function being invoked was created using `Function.bind()`, `this` will be the first argument that was passed to `.bind()` at the time the function was created.
13
13
- If the function is being invoked as a method of an object, `this` will refer to that object.
14
14
- Otherwise, the function is being invoked as a standalone function not attached to any object, and `this` will refer to the global object.
15
15
16
16
```
17
-
// A function invoked using Function.call
17
+
// A function invoked using Function.call()
18
+
18
19
var myObject = {
19
20
sayHello: function() {
20
21
console.log( "Hi! My name is " + this.myName );
@@ -31,7 +32,8 @@ myObject.sayHello.call( secondObject ); // "Hi! My name is Colin"
31
32
```
32
33
33
34
```
34
-
// A function created using Function.bind
35
+
// A function created using Function.bind()
36
+
35
37
var myName = "the global object";
36
38
var sayHello = function() {
37
39
console.log( "Hi! My name is " + this.myName );
@@ -41,12 +43,13 @@ var myObject = {
41
43
};
42
44
var myObjectHello = sayHello.bind( myObject );
43
45
44
-
sayHello(); // "Hi! My name is the global object"
46
+
sayHello(); // "Hi! My name is the global object"
45
47
myObjectHello(); // "Hi! My name is Rebecca"
46
48
```
47
49
48
50
```
49
51
// A function being attached to an object at runtime.
0 commit comments