[英]Change the first argument in a function
I would like to do something like this: 我想做这样的事情:
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', '!');
Your code actually works (I just tested in Firefox, latest version). 您的代码实际上有效(我刚刚在Firefox中测试过,最新版本)。
However, I could imagine that some implementations may have a problem with the arguments
object when passing in as value to Function.prototype.apply
. 但是,我可以想象,当作为值传递给
Function.prototype.apply
时,某些实现可能会出现arguments
对象的问题 。 So try: 所以尝试:
function start(){
var args = Array.prototype.slice.call( arguments );
args[0] = '<h1>' + args[0] + '</h1>';
log.apply(this, args);
}
By invoking Array.prototype.slice
on the arguments
-object, we create a " true " ECMAscript Array , which we might need as second argument for .apply()
通过在
arguments
Array.prototype.slice
上调用Array.prototype.slice
,我们创建一个“ true ”ECMAscript 数组 ,我们可能需要它作为.apply()
第二个参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.