Module2: Demo: Using This Keyword

jason.zhu 2021-05-12 12:27:54 +10:00
parent f6de87bb39
commit 9cb35c02c3

@ -61,3 +61,28 @@ let greeting = name => 'Hello ' + name;
let message = greetings('John');
console.log(message);
```
## Bahavior of `this` Keyword
`this` of regular function:
* refers to the owner of the function we are executing
* for standalone function, `this` refers global window obj
* for function within object, `this` refers the object
`this` of arrow function
* Unlike regular functions, arrow functions do not have their own `this` value
### Demo
```javascript
let message = {
name: 'John',
regularFunction: function() {
console.log(this);
},
arrowFunction: () => console.log(this)
}
message.regularFunction(); // {name: "John", regularFunction: f, arrowFunction: f}
message.arrowFunction(); // {window: Window, self: Window, document: document, name: "", ...}
```