簡體   English   中英

通過window對象引用它們時,全局變量未定義

[英]Global variables undefined when referencing them via window object

我通過窗口全局聲明變量是相當新的,所以我有點驚訝,以下代碼段的行為取決於瀏覽器。

window.test = "Good";
document.write(window.test);
document.write('<br>');
document.write(window.test);
document.write('<br>');
document.write(test);​

Firefox,IE,Opera

未定義

Chrome和Safari

我最初的信念是它應該像Chrome和Safari那樣表現,但我意識到我可能沒有正確理解窗口對象,那么更有知識的人會解釋這個嗎?

我意識到我可以使用var test = "Good"; 對於該范圍,但我感興趣的是為什么瀏覽器以不同的方式處理它。

http://jsfiddle.net/WHYFc/

你的JSFiddle使用window.load來創建腳本。

document.write加載CLEARS / WIPES文件之后你所看到的對於那些瀏覽器是正常的而webkit只是更寬松

這是你在jsfiddle中生成的代碼:

window.addEvent('load', function() {
window.test = "Good";
document.write(window.test);
document.write('<br>');
document.write(window.test);
document.write('<br>');
document.write(test);
});

將你的小提琴改為頭部或身體,它將按預期工作

DEMO

如果你想在全局存儲某些東西,即使你正在打開新文檔,你也可以(有點諷刺的是)使用document對象,這似乎是持久的。

document.test = "Good";

document.write(document.test); // > "Good"
document.write('<br>');
document.write(document.test); // > "Good"
document.close();

setTimeout(() => {
    document.write("Also " + document.test); // > "Also Good"
    document.close();
}, 2000);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM