1

So, The example below run just fine and dandy.

document.write("<pre>");
try {
    document.writeln( document.querySelector );
    document.writeln( "example".indexOf );
    
    (function(x){
        var f=x;
        document.writeln( f + ",\n\t" + x.toString() );
    })( "example".indexOf );
    
    (function(x){ document.writeln(
        typeof x === typeof document.querySelector
    ) })( document.querySelector );
} catch(e) { document.writeln(
    "<span style='color:red'>" + e + "</span>"
) };
document.write("</pre>");

So, those built-in functions appear to be referenceable because they can be passed as arguments, used as variables, and they retain their object prototype (the toString, at least). However, in chrome (at least), things get very strange and a typeerror: illegal invocation

document.write("<pre>");
try {
    (function(x){
        var f=x;
        document.writeln( f() );
    })( "example".indexOf );
    
    (function(x){ document.writeln(
        x()
    ) })( document.querySelector );
} catch(e) { document.writeln(
    "<span style='color:red'>" + e + "</span>"
) };
document.write("</pre>");

My questions are:

  • Why does this error occur?
  • Is this error part of the W3 standard? If so, then please cite.
  • What browsers will this error or similar errors occur in?
  • Are there any clever ways around this error other than a proxy function1, because something like this would be amazing for minifying scripts to be even smaller.

Note1: "proxy function" example:

function proxy(x){
    return document.querySelector(x);
}
  • 2
    This might be helpful: https://stackoverflow.com/questions/9677985/uncaught-typeerror-illegal-invocation-in-chrome – Alex Patch Apr 21 '17 at 18:33
  • 2
    Or this: https://stackoverflow.com/questions/10743596/why-are-certain-function-calls-termed-illegal-invocations-in-javascript – Alex Patch Apr 21 '17 at 18:34

0 Answers0