问题
John Resig wrote:
Finally, a long-standing (and very annoying) bug has been resolved: Cases where null or undefined is coerced into becoming the global object. Strict mode now prevents this from happening and throws an exception instead.
(function(){ ... }).call( null ); // Exception
what bug is he referring to?
回答1:
Basically, you are using the call()
method from Function.prototype
, which by default takes scope as the first parameter. If execution scope is undefined
or null
, it defaults to the global object. In some situations, using the call
method with an Immediately Invoked Function Expression(the above code is rather uncommon) doesn't use the global object as the default fallback execution scope.
If this is evaluated within strict mode code, then the this
value is not coerced to an object. A this
value of null
or undefined
is not converted to the global object and primitive values are not converted to wrapper objects. The this value passed via a function call (including calls made using Function.prototype.apply
and Function.prototype.call
) do not coerce the passed this
value to an Object
(10.4.3, 11.1.1, 15.3.4.3, 15.3.4.4 clauses of the ECMA language specification).
来源:https://stackoverflow.com/questions/13997247/cases-where-null-or-undefined-is-coerced-into-becoming-the-global-object