Person.prototype.fullname = function(joiner, options) {
options = options || { order: "western" };
var first = options.order === "western" ? this.first : this.last;
var last = options.order === "western" ? this.last : this.first;
return first + (joiner || " ") + last;
};
// Create an unbound version of "fullname", usable on any object with 'first'
// and 'last' properties passed as the first argument. This wrapper will
// not need to change if fullname changes in number or order of arguments.
Person.fullname = function() {
// Result: Person.prototype.fullname.call(this, joiner, ..., argN);
return Function.call.apply(Person.prototype.fullname, arguments);
};
来自 Javascript Garden 的代码。
请注意,它声明了
Function.call.apply(Person.prototype.fullname, arguments);
会变成这样:
Person.prototype.fullname.call(this, joiner, ..., argN);
这意味着首先执行apply()函数,然后执行call()函数。
模式:最右边 call() / apply()的将首先被执行
- 所以最正确的
apply()将首先被执行
- 的上下文
apply()成为call()函数的调用者,所以现在Person.prototype,fullname.call()
apply()只能接受一个参数数组,所以apply()提供arguments给call()函数,所以现在Person.prototype,fullname.call(参数)
来自@foxiris 的示例
第一个:
Function.apply.call(Array,this,[1,2])
- 最正确
call()的将首先被执行
- 的上下文
call()成为 的调用者apply(),所以现在Array.apply()
call()可以接受多个参数,所以它可以提供和thisto [1, 2],apply()所以 now Array.apply(this, [1, 2]);,它将输出[1, 2]
第二个:
Function.call.apply(Array,this,[1,2])
- 最正确
apply()的将首先被执行
- 的上下文
apply()成为 的调用者call(),所以现在Array.call()
apply()只能接受一个数组参数,所以它只能提供给this,call()所以现在Array.call(this);,输出是[]。
第三个:
Function.call.call(Array,this,[1,2])
- 最正确
call()的将首先被执行
- (最右边的)的上下文
call()变成了(右边第二个)的调用者call(),所以现在Array.call()
- 可以接受多个参数,
call()所以它可以提供this和[1, 2]给另一个call(),所以现在Array.call(this, [1, 2]);,输出是[[1, 2]]。