2016-07-22 117 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