-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
function-call.html
68 lines (57 loc) · 1.62 KB
/
function-call.html
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
66
67
68
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
// Title: 4 different ways to call function
var foo, bar, baz, myapp;
function foo(a, b) {
return [this, a, b];
};
// using () operator
// if the function is called without an explicit owner object
// `this` keyword will refers to global
//
// bar = [window, 1, 2]
bar = foo(1, 2);
console.log(bar);
myapp = {
baz: foo,
onemore: function() {
function insideTheClosure() {
return this;
}
return [this, insideTheClosure()]
}
};
// still using () operator
// but now baz function belongs to myapp object
//
// bar = [myapp, 1, 2]
bar = myapp.baz(1, 2);
console.log(bar);
// like in the first example we need to call function
// within myapp like myapp.baz()
// not just inside the object`s function
//
// bar = [myapp, window]
bar = myapp.onemore();
console.log(bar);
// using apply and call methods of the Function itself
// there are almost the same
// but apply could be useful in case we don't know arguments beforehand
//
// bar = [myapp, 1, 2]
bar = foo.call(myapp, 1, 2);
console.log(bar);
bar = foo.apply(myapp, [1, 2]);
console.log(bar);
/* Reference:
* http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/JavaScript-5-ways-to-call-a-function.aspx
*/
</script>
</body>
</html>