// same as "slice" in the previous example
var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.apply.bind(unboundSlice);
// ...
slice(arguments);
当我像下面这样写时
function add(num1, num2){
return num1 + num2;
}
var test = Function.prototype.apply.bind(add);
var result = test([1,2])
这是错误的。 我不知道我的代码哪里错了。
最佳答案
Function.prototype.apply
不仅仅需要参数列表的 [1, 2]
参数 - 它需要 this
参数在它之前。 (docs)换句话说,您的代码实际上正在做的是:
function add(num1, num2){
return num1 + num2;
}
var result = add.apply([1, 2]);
你想要的是这样的:
function add(num1, num2){
return num1 + num2;
}
var result = add.apply(null, [1, 2]);
因此可以实现:
function add(num1, num2) {
return num1 + num2;
}
var test = Function.prototype.apply.bind(add, null);
var result = test([1, 2]);
console.log(result);
关于javascript - 绑定(bind)和应用是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47524273/