call apply bind

Solutions on MaxInterview for call apply bind by the best coders in the world

showing results for - "call apply bind"
Marge
26 Jul 2019
1Answer in SIMPLEST form
2
3Call invokes the function and allows you to pass in arguments one by one.
4Apply invokes the function and allows you to pass in arguments as an array.
5Bind returns a new function, allowing you to pass in a this array and any number of arguments.
6
7Apply vs. Call vs. Bind Examples
8--------------
9Call
10
11var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
12var person2 = {firstName: 'Kelly', lastName: 'King'};
13
14function say(greeting) {
15    console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
16}
17
18say.call(person1, 'Hello'); // Hello Jon Kuperman
19say.call(person2, 'Hello'); // Hello Kelly King
20
21--------------
22Apply
23
24var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
25var person2 = {firstName: 'Kelly', lastName: 'King'};
26
27function say(greeting) {
28    console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
29}
30
31say.apply(person1, ['Hello']); // Hello Jon Kuperman
32say.apply(person2, ['Hello']); // Hello Kelly King
33
34-------------
35Bind
36
37var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
38var person2 = {firstName: 'Kelly', lastName: 'King'};
39
40function say() {
41    console.log('Hello ' + this.firstName + ' ' + this.lastName);
42}
43
44var sayHelloJon = say.bind(person1);
45var sayHelloKelly = say.bind(person2);
46
47sayHelloJon(); // Hello Jon Kuperman
48sayHelloKelly(); // Hello Kelly King
Lisa
28 Jan 2019
1const obj = { number: 1 }
2
3function foo() {
4	console.log(this.number)
5}
6
7//bind - binds obj's 'this' context to foo, but doesn't call it
8const newFoo = foo.bind(obj) 
9
10//call/apply - binds obj's 'this' context to foo, then calls it
11foo.call(obj, /*arg1*/, /*arg2*/) 
12foo.apply(obj, [/*arg1*/, /*arg2*/])
13
14//Only difference between call/apply is argument passing - ',' vs '[]'
15