【发布时间】:2018-10-29 11:20:28
【问题描述】:
这次我真的对Javascript感到困惑:
var x = Array.prototype.concat.call;
typeof x; // function
x(); // Uncaught TypeError: x is not a function
这到底是怎么回事?
如果有帮助,我还注意到:
x([1,2],[3,4])也不起作用-
toString也认为是函数:Object.prototype.toString.call(x); // "[object Function]" Array.prototype.concat.apply也会发生这种情况。-
当它被强制作为表达式时它也不起作用:
(0, Array.prototype.concat.call)([1,2],[3,4]); // Same TypeError
在 Chrome 和 Node 中测试。
【问题讨论】:
-
这只是错误信息中的一个错误(不是函数的东西是
x()的this,而不是x)。 Firefox 是正确的,例如:“TypeError: Function.prototype.call called on incompatible undefined” -
spec 表示应该抛出
TypeError,但不是特定消息应该是什么。 -
@Ry- 你能澄清一下吗?请注意,
x([1,2],[3,4])也不起作用。 -
@Hamsterrific:
Array.prototype.concat.call === Function.prototype.call。重要的是你如何调用call——它的this值决定了被调用的函数。x()的this值为undefined。var x = Function.prototype.call.bind(Array.prototype.concat);可能是有意为之(但错误消息仍然是错误的,与var x = Array.prototype.concat.bind([])相比仍然会更好)。 -
toString = Function.prototype.toString; toString()->Uncaught TypeError: Function.prototype.toString requires that 'this' be a Function看起来错误不一致。
标签: javascript function typeerror