@@ -38,23 +38,37 @@ another.
38
38
// do stuff here
39
39
}
40
40
41
- Another trick is to use both ` call ` and ` apply ` together to create fast, unbound
42
- wrappers .
41
+ Another trick is to use both ` call ` and ` apply ` together to turn methods - functions that use the
42
+ value of ` this ` as well as their arguments - into normal functions which only use their arguments .
43
43
44
- function Foo() {}
44
+ function Person(first, last) {
45
+ this.first = first;
46
+ this.last = last;
47
+ }
45
48
46
- Foo.prototype.method = function(a, b, c) {
47
- console.log(this, a, b, c);
49
+ Person.prototype.fullname = function(joiner, options) {
50
+ options = options || { order: "western" };
51
+ var first = options.order === "western" ? this.first : this.last;
52
+ var last = options.order === "western" ? this.last : this.first;
53
+ return first + (joiner || " ") + last;
48
54
};
49
55
50
- // Create an unbound version of "method"
51
- // It takes the parameters: this, arg1, arg2...argN
52
- Foo.method = function() {
53
-
54
- // Result: Foo .prototype.method .call(this, arg1, arg2 ... argN)
55
- Function.call.apply(Foo .prototype.method , arguments);
56
+ // Create an unbound version of "fullname", usable on any object with 'first'
57
+ // and 'last' properties passed as the first argument. This wrapper will
58
+ // not need to change if fullname changes in number or order of arguments.
59
+ Person.fullname = function() {
60
+ // Result: Person .prototype.fullname .call(this, joiner, ..., argN);
61
+ return Function.call.apply(Person .prototype.fullname , arguments);
56
62
};
57
63
64
+ var grace = new Person("Grace", "Hopper");
65
+
66
+ // 'Grace Hopper'
67
+ grace.fullname();
68
+
69
+ // 'Turing, Alan'
70
+ Person.fullname({ first: "Alan", last: "Turing" }, ", ", { order: "eastern" });
71
+
58
72
59
73
### Formal Parameters and Arguments Indices
60
74
0 commit comments