片段1:
window.onload = function() {
var friendlyChat = new FriendlyChat();
};
var sample = function() {
var sampleInstance = friendlyChat; //error
// friendlyChat cannot be accesses here as you have declared it
// at function scope which gets destroyed once the function has
// returned or completed the execution.
}
friendlyChat
是局部變量並且可以此函數內部僅訪問。
片段2:
window.onload = function() {
window.friendlyChat = new FriendlyChat();
};
var sample = function() {
var sampleInstance = friendlyChat;
// friendlyChat can be accesses here as you have declared it at
// windows scope which is available globally.
}
friendlyChat
是一個全局變量,因爲它已經在根級別即窗口被宣佈可以在任何地方訪問。
第一個創建一個局部變量;第二個創建一個全局變量。 – gyre
也許這裏可能是一個寶貴的資源:https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/ – haxxxton