Skip to content

Commit f10e3e6

Browse files
authored
Added this and context
1 parent ff36336 commit f10e3e6

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

README.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,3 +66,47 @@ try {
6666
}
6767
console.log(e) // Uncaught ReferenceError: e is not defined
6868
```
69+
## Context
70+
Often scope and context are confused among the developers. Scope refers to the visibility of the variable and context refers to the value of the `this` keyword.
71+
72+
### `this` in Global scope
73+
In a global scope, `this` always refers to the `window` object. All global JavaScript objects, functions, and variables automatically become members of the `window` object.
74+
```
75+
console.log(this);
76+
// logs: Window {postMessage: f, blur: f, focus: f, frames: Window, …}
77+
```
78+
### `this` with new
79+
If scope is in the method of an object, context will be the object the method is part of.
80+
```
81+
function User() {
82+
console.log(this);
83+
}
84+
new User(); // User {}
85+
```
86+
If we call a function using the `new` keyword, the context will then be set to the instance of the called function.
87+
88+
### `this` with bind
89+
If we bind a function explicitly with some object, then the `this` inside function will be set to the object we bind.
90+
```
91+
function greet() {
92+
console.log('Hello ' + this.name);
93+
}
94+
var obj = { name: 'John Doe' };
95+
var greetFn = greet.bind(obj);
96+
greetFn(); // Hello John Doe
97+
98+
// calling greet function normally will take window object for this.
99+
var name = 'Albert';
100+
greet(); // Hello Albert
101+
```
102+
### `this` inside method
103+
If we call a method of an object, then `this` will be automatically set to the current object.
104+
```
105+
var obj = {
106+
name: 'John Doe',
107+
greet: function() {
108+
console.log('Hello ' + this.name);
109+
}
110+
};
111+
obj.greet(); // Hello John Doe
112+
```

0 commit comments

Comments
 (0)