Javascript Uncaught TypeError: Function.prototype.apply: Arguments list has wrong type (?)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5988326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:46:46  来源:igfitidea点击:

Uncaught TypeError: Function.prototype.apply: Arguments list has wrong type (?)

javascript

提问by Justin808

I'm getting the error Uncaught TypeError: Function.prototype.apply: Arguments list has wrong typewhen I use the .apply()method and I'm not sure why. My code is here.

Uncaught TypeError: Function.prototype.apply: Arguments list has wrong type使用该.apply()方法时出现错误,但不知道为什么。我的代码在这里

When jsfiddle loads up, click next to the word test and hit the Enter key. The method that the error is occurring in is this.addEvent. I'm trying to have my object be the 'this' in the event's callback function.

当 jsfiddle 加载时,单击 test 旁边的单词并按 Enter 键。发生错误的方法是this.addEvent。我试图让我的对象成为事件回调函数中的“this”。

回答by kennytm

You should use .callinstead of .apply.

你应该使用.call而不是.apply.

a.apply(obj, lst)is equivalent to a(lst[0], lst[1], lst[2], ...)when lstis an Array (or arguments) using objas this.

a.apply(obj, lst)等价于a(lst[0], lst[1], lst[2], ...)whenlst是一个arguments使用objas的数组(或)this

a.call(obj, x, y, z, ...)is equivalent to a(x, y, z, ...)using objas this.

a.call(obj, x, y, z, ...)相当于a(x, y, z, ...)使用objas this

Since eis one of the arguments, not an array of arguments, you should use .call.

由于e是参数之一,而不是参数数组,因此您应该使用.call.

回答by KooiInc

applyexpects an array object. You can also use callif you want to supply arguments directly. You can also convert arguments to an array using apply

apply需要一个数组对象。call如果您想直接提供参数,也可以使用。您还可以使用以下方法将参数转换为数组apply

func.apply(editorObject, [e]); //=> apply expects an array of arguments
func.call(editorObject, e);    //=> call receives arguments directly