2016-05-05 45 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"); 

我想通過外部函數foo2更改foo1參數值。我通過在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),那麼如果我引用它們(而參數[0],參數[1]返回新值),則a和b保持不變。 –

+0

@Paweł查看更新。 – iplus26

0

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

如果你返回從foo2剛剛設置參數的兩個新的參數到返回值:

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

好,我發現分辨率。我剛剛將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"); 
相關問題