2016-05-05 44 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"); 
相关问题