function sumArguments () {
var value = this instanceof Number ? this : 0;
for (var i = 0; i < arguments.length; i++) {
value += arguments[i];
}
return value;
}
Function.prototype.apply1 = function() {
var fn = this;
var args = Array.prototype.slice.call(arguments);
var context = args.shift();
var newArgs = args[0];
var boundfn = fn.bind(context, newArgs);
return boundfn();
}
console.log(sumArguments.apply1(4, [1, 2, 3])); --> should equal 10
如何在不使用apply的情况下应用实现?我遇到了如何将1,2,3的数组转换为要绑定的1,2,3的问题。
发布于 2015-12-19 09:01:02
我能想到的唯一方法就是使用eval
。
function apply(fn, args){
var stringArgs = args.reduce(function(acc, el, i){
var argString = 'args[' + i + ']';
return acc += i === 0 ? argString : ',' + argString;
});
return eval('fn(' + stringArgs + ')');
}
function test(first, second, third){
console.log(first, second, third);
}
apply(test, [1, 2, 3]);
不过,我不明白你为什么需要这个。这也不适用于许多数据类型,如对象或字符串。不过,它确实适用于数字。
编辑:现在它适用于任何数据类型。
发布于 2015-12-19 09:25:34
这里的目标是使用上下文和提供的参数调用fn.bind
,对吗?
如果您使用的是ES6,则扩展运算符...
就是您想要的:
foo(...[1,3,5]); //equivalent to foo(1, 3, 5)
fn.bind(context, ...args);
否则,您可以在bind
上调用apply
fn.bind.apply(fn, [context].concat(args));
将fn
作为fn.bind
的上下文传递将保持其正常行为,并且您需要组合要传递的所有参数以绑定到单个数组中,因此需要进行连接。
发布于 2015-12-19 09:17:59
我不确定为什么需要使用apply,但这里的sum函数可以满足您的需求。它应该能够处理许多内部数组并忽略对象。
function sumArguments() {
var value = this instanceof Number ? this : 0;
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] === 'number') {
value += arguments[i];
} else if (typeof arguments[i] === 'object' &&
typeof arguments[i].length !== 'undefined') {
for (var j = 0; j < arguments[i].length; j++) {
if (typeof arguments[i][j] === 'number') {
value += arguments[i][j];
} else if (typeof arguments[i][j] === 'object' &&
typeof arguments[i][j].length !== 'undefined') {
value += sumArguments(arguments[i][j]);
}
}
}
}
return value;
}
console.log(sumArguments(4, [1, 2, 3, [7, 8]], 5, 'a', 2));
https://stackoverflow.com/questions/34366035
复制相似问题