我是Javascript的新手,对下面的代码片段之间的区别感到有点困惑。
摘录1:
window.onload = function() {
var friendlyChat = new FriendlyChat();
};
摘录2:
window.onload = function() {
window.friendlyChat = new FriendlyChat();
};
有人可以告诉他们之间的区别吗?
答案 0 :(得分:5)
摘录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
是一个全局变量,可以在任何地方访问,因为它已在根级别声明,即窗口。