4

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', '!');
Adam Halasz
  • 57,421
  • 66
  • 149
  • 213
  • Note that `print` is already a built-in function. – Waleed Khan Jan 06 '13 at 03:52
  • 2
    The fact that `arguments` isn't an array might be causing a problem when you pass it on to the apply function: _The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length._ - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments – João Paulo Macedo Jan 06 '13 at 03:55

1 Answers1

5

Your code actually works (I just tested in Firefox, latest version).

However, I could imagine that some implementations may have a problem with the arguments object when passing in as value to Function.prototype.apply. 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()

jAndy
  • 231,737
  • 57
  • 305
  • 359
  • you are right my code works! In my production code I'm trying to use apply on `console.log` and that's why it doesn't works. I just need to change the context to console. But anyway your answer was helpful and I just realized that I can use simple arrays with apply :) – Adam Halasz Jan 06 '13 at 04:05