Skip to content

Commit ebfd151

Browse files
committed
Merge pull request BonsaiDen#262 from BonsaiDen/less-horrible-example-for-call-apply
improve example code for call.apply
2 parents 1ac6aaa + 543ac57 commit ebfd151

File tree

1 file changed

+25
-11
lines changed

1 file changed

+25
-11
lines changed

doc/en/function/arguments.md

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -38,23 +38,37 @@ another.
3838
// do stuff here
3939
}
4040

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.
4343

44-
function Foo() {}
44+
function Person(first, last) {
45+
this.first = first;
46+
this.last = last;
47+
}
4548

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;
4854
};
4955

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);
5662
};
5763

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+
5872

5973
### Formal Parameters and Arguments Indices
6074

0 commit comments

Comments
 (0)