更改函数中的第一个参数

Ada*_*dam 4 javascript arguments function apply

我想做这样的事情:

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', '!');
Run Code Online (Sandbox Code Playgroud)

jAn*_*ndy 5

您的代码实际上有效(我刚刚在Firefox中测试过,最新版本).

不过,我可以想像,一些实现可能有一个问题arguments传递的值时,对象Function.prototype.apply.所以尝试:

function start(){
    var args = Array.prototype.slice.call( arguments );
    args[0] = '<h1>' + args[0] + '</h1>';

    log.apply(this, args);
}
Run Code Online (Sandbox Code Playgroud)

通过调用Array.prototype.slicearguments-object,我们创建了一个" 真实 "的EcmaScript 阵列,我们可能需要作为第二个参数.apply()