2016-07-22 76 views
0

由于我的js类的性质,我有一个共同的参数分隔符。我不知道如何applycall,这个functin和通过arguments对象,而不实际传递它作为函数的参数。传递参数

function splitArgs(){ 
    return { 
     text : arguments[0], 
     class : arguments[1] || "" 
    } 
} 

function doSomething(){ 
    var args = splitArgs.call(this, arguments); 
    if(args.class) 
     // do stuff 
} 

我已经试过

splitArgs.call(this, arguments);

splitArgs.call(this, ...arguments);

splitArgs.apply(this, arguments);

splitArgs.apply(this, ...arguments);

splitArgs(...arguments);

回答

0

我知道你说你试过splitArgs.apply(this, arguments) ...但它似乎为我工作:

function splitArgs() { 
 
    return { 
 
     text: arguments[0], 
 
     class: arguments[1] || "" 
 
    }; 
 
} 
 

 
function doSomething() { 
 
    var args = splitArgs.apply(this, arguments); 
 
    console.log(args); 
 
} 
 

 
doSomething('foo', 'bar'); 
 

 
// Output: 
 
// { text: 'foo', class: 'bar' }

输出:

{ text: 'foo', class: 'bar' } 

随着ES6,这也适用对我来说:

var args = splitArgs(...arguments); 
+0

你的小提琴适合我。 (我做了'新Foo()。do(“foo”,“bar”)',然后两者都有效。)**编辑**:这是对自从删除评论的回应。 – smarx

+0

thx。我有更多的争论问题,把所有参数都放到第一个参数中! – Tester232323