IE8 error assigning a function() to a property nam

2019-09-06 14:20发布

问题:

Consider running the following code in IE8 and Chrome consoles to compare:

var a = function(){ console.log("function is() initialized"); };

// assign a property named 'function' to function 'a'

a.function = function afunction(f){ return (typeof f === 'function'? true: false); };

// Use our is function to test if a given variable is a function

a.function(a); // IE throws 'expected identifier' error v/s Chrome correctly outputs "true"

Any ideas how this can be tackled in IE8 without changing function signature: a.function()?

回答1:

Use the alternate property access syntax, which is immune to interference from reserved words:

a["function"](a);