“强制将null或undefined强制成为全局对象的情况”。 [英] "cases where null or undefined is coerced into becoming the global object"

查看:97
本文介绍了“强制将null或undefined强制成为全局对象的情况”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

John Resig 写了


最后,一个长期(并且非常烦人)的错误已经解决:将null或undefined强制转换为全局对象的情况。严格模式现在可以防止这种情况发生并引发异常。



(function(){...})。call(null); //异常


他指的是什么错误?

解决方案

基本上,您使用 Function.prototype中的 call()方法,默认情况下将范围作为第一个参数。如果执行范围是 undefined null ,则默认为全局对象。在某些情况下,使用带有立即调用的函数表达式的调用方法(上面的代码相当罕见)不会将全局对象用作默认的回退执行范围。 / p>

如果在严格模式代码中评估此值,则值不会强制转换为对象。 null undefined 未转换为全局对象和原始值不会转换为包装器对象。此值通过函数调用传递(包括使用 Function.prototype.apply Function.prototype.call 进行的调用) )不要将传递的值强制转换为对象(10.4.3,11.1.1,15.3.4.3, 15.3.4.4 ECMA语言规范的条款)。


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?

解决方案

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).

这篇关于“强制将null或undefined强制成为全局对象的情况”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆