.call 和 .apply 之间的区别
有没有一种简单的方法可以将所有参数从一个函数传递到另一个函数并发送 this
。
我已经尝试过这个: http://jsfiddle.net/v92Xr/
var f1 = function() {
f2.call(this, arguments);
};
var f2 = function() {
console.log(arguments);
};
f1("abc", "def", "hij");
但它给我留下了 f1 的所有参数堆叠在 f2 参数 0 中:
f2->arguments[0] == f1->arguments
好的,当我运行 apply
方法时,它会起作用:http://jsfiddle.net/v92Xr/1/
var f1 = function() {
f2.apply(this, arguments);
};
var f2 = function() {
console.log(arguments);
};
f1("abc", "def", "hij");
那么谁能告诉我 call
和 apply
之间有什么区别? ?
Is there a simple way to passing all arguments from one function to another and sending this
also.
I have tried this: http://jsfiddle.net/v92Xr/
var f1 = function() {
f2.call(this, arguments);
};
var f2 = function() {
console.log(arguments);
};
f1("abc", "def", "hij");
but it leaves me all the arguments from f1 is stacked in f2 arguments 0:
f2->arguments[0] == f1->arguments
Ok and when i run the apply
method instead it works: http://jsfiddle.net/v92Xr/1/
var f1 = function() {
f2.apply(this, arguments);
};
var f2 = function() {
console.log(arguments);
};
f1("abc", "def", "hij");
So can anyone please tell me what's the difference between call
and apply
is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想您自己已经发现了其中的差异。
call
与通常调用函数的方式几乎相同,只是在参数列表的开头有一个额外的参数,您可以在其中放置this
对象的引用。apply
也将第一个参数作为this
对象,但第二个参数应该是一个数组。该数组用于提供被调用函数所需的所有参数。元素 0 映射到函数参数列表中的第一个参数,元素 1 映射到第二个,依此类推。I think you've just discovered the difference yourself.
call
is almost identical to way you would normally call a function except there is an extra parameter at the start of the parameter list where you place the reference for thethis
object.apply
also has the first parameter as thethis
object but the second parameter is expected to be an array. This array is used to supply all the arguments that the called function is expecting. Element 0 maps to the first argument in the functions argument list, element 1 to the second and so on.调用 MDN:https://developer.mozilla .org/en/JavaScript/Reference/Global_Objects/Function/call
申请 MDN:https://developer.mozilla .org/en/JavaScript/Reference/Global_Objects/Function/apply
call MDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call
apply MDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply