gpt4 book ai didi

javascript - 如何在不使用apply的情况下实现Function.prototype.apply?

转载 作者:行者123 更新时间:2023-12-02 15:17:03 25 4
gpt4 key购买 nike

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 传递以进行绑定(bind)的困境。

最佳答案

我能想到的唯一方法是使用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]);

不过,我不明白你为什么需要这个。这也不适用于许多数据类型,例如对象或字符串。不过它确实适用于数字。

编辑:现在它适用于任何数据类型。

关于javascript - 如何在不使用apply的情况下实现Function.prototype.apply?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34366035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com