调用函数时如何动态的指定不定个数的参数?

Gdj 2009-08-26 12:17:57
js里有没有类似php的call_user_func_array函数?
即:call_user_func_array("test",array(1,2,3,4,5));
等价于 test(1,2,3,4,5);

得到一个不定长度的数组时应该如何作为参数传移到指定函数?
(被调用的函数无法改动,不能改成test(array param)的类型)
...全文
128 13 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
BeenZ 2009-08-26
  • 打赏
  • 举报
回复
不过一般会这样写,用于参数的绑定

var Bind = function(object, fun) {
var args = Array.prototype.slice.call(arguments, 2);
return function() {
return fun.apply(object, args.concat(Array.prototype.slice.call(arguments)));
}
}

这样参数就不止是array了,可以是object
顺便说下call这个函数 例:this.Function.call(this,arg); arg是参数,传递给Function函数
BeenZ 2009-08-26
  • 打赏
  • 举报
回复
例:

function test(val){
alert(val);
}
var sth=function(){
this.apply.test(this,[1,2,3,4,5])
}

调用sth函数会以[1,2,3,4,5]这个数组为参数传递给test(val)
BeenZ 2009-08-26
  • 打赏
  • 举报
回复
有, call函数和apply函数
linuxlsx 2009-08-26
  • 打赏
  • 举报
回复
好象没有, 期待解答
zhubo_1117 2009-08-26
  • 打赏
  • 举报
回复
这个真没有!
幸运的意外 2009-08-26
  • 打赏
  • 举报
回复
JavaScript函数有一个隐含的数组arguments,他记录了这个函数在调用时传入了几个参数。参数个数可以用arguments.length来得到。很多JavaScript模拟重载时就是利用这个隐含属性来实现的。
BeenZ 2009-08-26
  • 打赏
  • 举报
回复
因为回传的是一个function,一般在函数的闭包里使用,非常好用
我程序部分使用bind方法代码

addEvent( oContainer, "mouseover", Bind( this, function(){ clearTimeout(this._timerContainer); } ) );
Gdj 2009-08-26
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 xinyung 的回复:]
JScript codefunction test(a,b,c) {
alert(a+','+b+','+c);
}
test.apply(this,[1,2,3,4,5]);
[/Quote]

测试通过。感谢。
BeenZ 2009-08-26
  • 打赏
  • 举报
回复
不好意思,写错了

var Bind = function(object, fun) {
var args = Array.prototype.slice.call(arguments, 2);
return function() {
return fun.apply(object, args.concat(Array.prototype.slice.call(arguments)));
}
}
function test(a,b,c){
alert(a+','+b+','+c);
}

Bind( this, test,1,2,3,4)()

可以测试一下.不知道这样是否明白了呢?
xinyung 2009-08-26
  • 打赏
  • 举报
回复
function test(a,b,c) {
alert(a+','+b+','+c);
}
test.apply(this,[1,2,3,4,5]);
Gdj 2009-08-26
  • 打赏
  • 举报
回复

function test(a,b,c)
{
alert(a+','+b+','+c);
}
var Bind = function(object, fun) {
var args = Array.prototype.slice.call(arguments, 2);
return function() {
return fun.apply(object, args.concat(Array.prototype.slice.call(arguments)));
}
}
Bind(test,1,2,3);

这样测试了,test也未被调用。没有弹出结果。
BeenZ 2009-08-26
  • 打赏
  • 举报
回复
因为你用错了

Bind(test,1,2,3,4,5,6,7); 回调函数在前面
Gdj 2009-08-26
  • 打赏
  • 举报
回复
对不起,我测试
 function test(val){
alert(val);
}
var sth=function(){
this.apply.test(this,[1,2,3,4,5])
}
sth();

报错。


function test(a,b,c)
{
alert(a+','+b+','+c);
}
var Bind = function(object, fun) {
var args = Array.prototype.slice.call(arguments, 2);
return function() {
return fun.apply(object, args.concat(Array.prototype.slice.call(arguments)));
}
}
Bind([1,2,3],test);

得不到正确结果。

87,996

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧