apply的用法
apply的用法和call类似,区别在于,apply的第二个参数是一个数组
apply实现原理
apply的实现原理和call的类似,区别在于第二个参数的处理
Function.prototype.myApply = function(context, arr) {
var context = context || window;
context.fn = this;
var result;
if(!arr) {
result = context.fn;
} else {
var args = []
for(var i = 0; i < arr.length; i++) {
args.push('arr[' + i + ']');
}
result = eval('context.fn('+args+')');
}
return result;
}
// 测试一下
var value = 2;
var obj = {
value: 1
}
function bar(name, age) {
console.log(this.value); // 2
return {
value: this.value,
name: name,
age: age
}
}
bar.myApply(null); // 1
console.log(bar.myApply(obj, ['James', 20])); // {value: 1, name: "James", age: 20}