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)的类型)

解决方案 »

  1.   

    例: 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)
      

  2.   

    不过一般会这样写,用于参数的绑定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函数
      

  3.   

    对不起,我测试
     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);得不到正确结果。
      

  4.   

    因为你用错了Bind(test,1,2,3,4,5,6,7); 回调函数在前面
      

  5.   


    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也未被调用。没有弹出结果。
      

  6.   

    function test(a,b,c) {
    alert(a+','+b+','+c);
    }
    test.apply(this,[1,2,3,4,5]);
      

  7.   

    不好意思,写错了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)()可以测试一下.不知道这样是否明白了呢?
      

  8.   

    因为回传的是一个function,一般在函数的闭包里使用,非常好用
    我程序部分使用bind方法代码addEvent( oContainer, "mouseover", Bind( this, function(){ clearTimeout(this._timerContainer); } ) );
      

  9.   

    JavaScript函数有一个隐含的数组arguments,他记录了这个函数在调用时传入了几个参数。参数个数可以用arguments.length来得到。很多JavaScript模拟重载时就是利用这个隐含属性来实现的。