Examples Of Understanding JavaScript Apply, Call And Bind

apply, call and bind

They are the embedded method of a function. The following examples show usage to bind this object to a callback function to replace the global this.

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
var op = {a: 1};
var a = 2;

(function(){
console.log(this.a);
})() // 2

(function(){
console.log(this.a);
}()) // 2

(function(){
console.log(this.a)
}.apply(op))

(function(){
console.log(this.a)
}).call(op)

(function(){
console.log(this.a);
}).bind(op)() // 1

(function(){
console.log(this.a);
}.bind(op)()) // 1

(function(arg1, arg2){
console.log(this, arg1, arg2)
}).call(op, "ss", "sss")

(function(arg1, arg2){
console.log(this, arg1, arg2)
}).apply(op, ["ss", "sss"])

setTimeout(function(arg){
console.log(op, arg)
}.call(op, "ss"), 19, "sss") // {a: 1} "ss"