该错误具有误导性。 Xis一个函数,但它丢失了引用的函数(concat),这会引发错误
在 Firefox 上运行会出现更具描述性的错误
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Called_on_inknown_type https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Called_on_incompatible_type
它的意思是call
函数没有任何绑定。
同样,如果你采用这样的对象:
const a = {
b: 2,
test() {
console.log('hi', this.b);
}
};
const c = a.test;
c();
你会得到hi undefined
因为你已经失去了函数与 b 的关系。
您可以通过执行以下任一操作来解决此问题c.bind(a)()
or c.call(a)
The call
函数的行为类似。这将是相同的every函数,伪代码如下所示:
class Function {
constructor(functionDefinition) {
this.functionDefinition = functionDefinition;
}
call(newThis, ...args) {
// take this.functionDefinition, and call it with `this` and `args`
}
}
由于您正在提取调用函数,因此它会丢失与其关联的函数对象。
您可以通过将 concat 绑定到函数或使用 call on call 来解决此问题:-)
const a = []
const boundFn = a.concat.call.bind(a.concat)
console.log(boundFn([3], [1,2]));
// Or, you can use `call` to pass in the concat function
const callFn = a.concat.call;
console.log(callFn.call(a.concat, [4], [1,2]))