2016-05-05 12 views
0
function foo1(a,b){ 
    console.log(arguments); //["oldValue","oldValue"] 

    var newArguments = foo2.apply(this,arguments); 
    for (var i=0;i<arguments.length;i++){ 
     arguments[i] = newArguments[i]; 
} 
    console.log(arguments); //["newValue","newValue"] 
} 

function foo2(){ 
    arguments[0] = "newValue"; 
    arguments[1] = "newValue"; 
    console.log(arguments); //["newValue","newValue"] 
    return arguments; 
} 

foo1("oldValue","oldValue"); 

foo1引数の値を外部関数foo2で変更したいと思います。私はfoo2の新しい引数で配列を返し、foo1の引数をfoo1の返された配列に置き換えることでそれを行いました。それ以外の、よりエレガントな方法がありますか?Function.prototype.apply()で呼び出し元関数の引数を変更する方法は?

答えて

0

argumentsを直接受け取らないのはなぜですか?

function foo1() { 
    console.log('foo1', arguments); // foo1 { '0': 'oldValue', '1': 'oldValue' } 

    arguments = foo2.apply(this, arguments); 

    console.log('foo1', arguments); // foo1 { '0': 'newValue', '1': 'newValue' } 

} 

function foo2() { 
    arguments[0] = 'newValue'; 
    arguments[1] = 'newValue'; 
    console.log('foo2', arguments); // foo2 { '0': 'newValue', '1': 'newValue' } 
    return arguments; 
} 

foo1('oldValue', 'oldValue'); 


アップデート1

あなたもabを変更したいので、私は以下のように "もう一度" foo1を呼び出ししようとするだろう:

function foo1(a, b) { 
    console.log('foo1', arguments); 

    if (a === 'oldValue') // Detect if `arguments` has been changed or not. 
         // (You can also use a variable to record the change if you prefer.) 
    // If not, change the arguments and call `foo1` using the new arguments 
    return foo1.apply(this, foo2.apply(this, arguments)); 

    console.log('foo1 (after changed)', arguments , a, b); 
    // Do something you want to do originally in `foo1` 
} 

私はあなたができると仮定foo1の中の引数を変更するのではなく、新しい機能を作ってください。それは私にやや難解ですね。

+0

なぜダウン票ですか? – iplus26

+0

引数を直接受け取ったにもかかわらず、このfoo1(a、b)のようないくつかのプロパティを設定した場合、aとbは参照しても変わりません(arguments [0]、arguments [1]は新しい値を返します)。 –

+0

@Pawełアップデートをチェックしてください。 – iplus26

0

https://jsbin.com/jibodu/1/edit?js,console

あなただけのその戻り値に引数を設定しfoo2から2つの新しい引数を返す場合:

arguments = foo2(); 

フルコード:

function foo1(a,b){ 
    console.log(arguments); //["oldValue","oldValue"] 
    arguments = foo2(); 
    var newArguments = foo2.apply(this,arguments); 
    for (var i=0;i<arguments.length;i++){ 
     arguments[i] = newArguments[i]; 
} 
    console.log(arguments); //["newValue","newValue"] 
} 
0

[OK]を、私は解像度を見つけました。 apply()の最初のパラメータを「引数」に変更しました。これは呼び出し側関数の引数を参照し、 'this'は直接その値を変更できます。それにもかかわらず、サポートに感謝!

function foo1(a, b) { 
    foo2.apply(arguments,arguments); 
    console.log(arguments); //["newValue","newValue"] 
    console.log(a); //"newValue" 
} 
function foo2() { 
    this[0] = "newValue"; 
    this[1] = "newValue"; 
}; 
foo1("oldValue","oldValue"); 
関連する問題