2012-03-11 56 views

回答

2

在規範中沒有出現「獲取對全局對象的訪問權限」的短語,因此沒有明確的定義;但翻翻規範的附錄C(的嚴格模式影響的非規範上市),我認爲可以描述這種方式,唯一的限制,這是一個:

Assignment to an undeclared identifier or otherwise unresolvable reference does not create a property in the global object. When a simple assignment occurs within strict mode code, its LeftHandSide must not evaluate to an unresolvable Reference. If it does a ReferenceError exception is thrown (8.7.2).

所以你不允許添加屬性全局對象,而不使用varwindow.或諸如此類的東西,但沒有什麼可以阻止你獲得全局對象—甚至設置一個現有屬性的值的屬性。

(順便說一句,的§ 8.7.2的相關位是不是非常有意義外的範圍內,但爲了完整性,那就是:

3. If IsUnresolvableReference(V), then
    a. If IsStrictReference(V) is true, then
        i. Throw ReferenceError exception.
    b. Call the [[Put]] internal method of the global object, passing
        GetReferencedName(V) for the property name, W for the value,
        and false for the Throw flag.

1

我認爲「獲得對全局對象」從非全局對象/範圍內意味着對其進行訪問。因此,這將拋出一個引用錯誤:

function foo(){ 
"use strict"; 
bar = '3'; 
} 
foo(); //=> ReferenceError: bar is not defined 

換句話說,我會說,「嚴格模式」強制變量自己的範圍內分配。這就是爲什麼window.x完全有可能。

在另一方面,一個可以地址window在一個函數中:

function foo(){ 
"use strict"; 
window.bar = '3'; 
} 
foo();  //=> no error 
alert(bar); //=> 3 

因此,在本質上,use strict防止聲明變量不包含此關鍵字var沒有給自己命名空間的引用在非全球範圍內。

+0

這不會拋出:http://jsbin.com/ufokid/edit#javascript,html請參閱@ ruakh的答案。 – ripper234 2012-03-11 15:36:38

+0

是的,這是否證明了什麼? – KooiInc 2012-03-11 16:30:50

+1

我的意思是,這是一個完全有效的封閉,所以,這與什麼矛盾的事情? – KooiInc 2012-03-11 16:44:08

0

未申報的全局(實例變量沒有功能VAR)是一個實例,

另一個原因是,該方法呼叫適用不再轉換一個全局對象的基元 - (其中一個字符串變成了字符串,以及空值或未定義的傳遞窗口)作爲'this'值。

相關問題