-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbind.js
More file actions
38 lines (32 loc) · 815 Bytes
/
Copy pathbind.js
File metadata and controls
38 lines (32 loc) · 815 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Basic Implementation
*/
let user = {
firstName: "John",
};
function testFunc(){
console.log(this.firstName)
}
// Create a new function 'funcUser' with the 'this' parameter bound to user
let funcUser=testFunc.bind(user);
funcUser();
// Output : John
/**
* Advanced
*/
// Top-level 'this' is bound to 'globalThis' in scripts.
this.x = 9;
const module = {
x: 81,
getX() {
return this.x;
},
};
// The 'this' parameter of 'getX' is bound to 'module'.
console.log(module.getX()); // 81
const retrieveX = module.getX;
// The 'this' parameter of 'retrieveX' is bound to 'globalThis' in non-strict mode.
console.log(retrieveX()); // 9
// Create a new function 'boundGetX' with the 'this' parameter bound to 'module'.
const boundGetX = retrieveX.bind(module);
console.log(boundGetX()); // 81