-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBind Call Apply method.html
More file actions
65 lines (54 loc) · 1.92 KB
/
Copy pathBind Call Apply method.html
File metadata and controls
65 lines (54 loc) · 1.92 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!doctype html>
<html lang="en">
<head>
<title>Bind Call Apply method</title>
<meta charset="utf-8">
<script>
//OPEN CONSOLE TO SEE RESULTS
var person = {
firstname : "John",
lastname : "Doe",
getFullName: function() {
var fullName = this.firstname +" "+this.lastname;
return fullName;
}
}
var logHello = function() {
//here this.getFullName function will not be available as it is a property of variable 'person'. Also 'this' doesn't refer to the 'person'.
console.log("Hello " + this.getFullName());
}
//Therefore to refer 'this' to 'person' we will bind logHello expression to 'person' to use 'person' property getFullName.
//Bind creates a copy of logHello and set 'this' to the person object.
//But it doesn't make the function call.
var logHelloPerson = logHello.bind(person);
logHelloPerson();
console.log('--------------')
//here we are using parametrised function in logHello2 expression with two parameters.
var logHello2 = function(english, spanish) {
console.log(english+"... " + this.getFullName());
console.log(spanish+"... " + this.getFullName());
}
var logHelloPerson2 = logHello2.bind(person);
//passing arguments.
logHelloPerson2('Hello', 'Hola');
console.log('--------------');
//call method enables us to set 'this' and call the logHello or logHello2 function as well. We can also pass arguments if required.
logHello.call(person);
logHello2.call(person, 'Hello', 'Hola');
console.log('--------------');
//same as call. But for apply we pass arguments in an array.
logHello.apply(person);
logHello2.apply(person, ['Hello', 'Hola']);
console.log('--------------');
//another apply example
var person2 = {
firstname: "Jane",
lastname: "Doe"
}
//suppose person2 wants to borrow getFullName function from person.
//Therefore using apply method to set this to point to person2 and the required property to person2.
console.log(person.getFullName.apply(person2));
</script>
</head>
<body> </body>
</html>