我想做这样的事情:
function start(){
// Change the first argument in the argument list
arguments[0] = '<h1>' + arguments[0] + '</h1>';
// Call log with the new arguments
// But outputs: TypeError: Illegal invocation
log.apply(this, arguments);
}
function log(){
console.log(arguments);
// should output -> ['<h1>hello<h1>', 'world', '!']
}
start('hello', 'world', '!');
最佳答案
您的代码确实有效(我刚刚在最新版本的 Firefox 中测试过)。
但是,我可以想象某些实现在将值作为值传递给 Function.prototype.apply
时,arguments
对象可能会出现问题>。所以尝试:
function start(){
var args = Array.prototype.slice.call( arguments );
args[0] = '<h1>' + args[0] + '</h1>';
log.apply(this, args);
}
通过在 arguments
对象上调用 Array.prototype.slice
,我们创建了一个“true”ECMAscript Array,我们可能需要它作为 .apply()
关于javascript - 更改函数中的第一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14179076/