1> window 作用域中声明变量
var type = "Red",attack = function() {
console.log( type + " Bird Attacks!" );
};
console.log( window.type ); // I'm a global variable
console.log( window.attack ); // I'm a global function
2> 任何作用于未声明的对象
var type = "Red",
attack = function() {
typeOfBird = type + " Bird";
return typeOfBird + " Bird Attacks!";
};
console.log( window.type ); // I'm a global variable
console.log( window.attack() ); // I'm a global function
console.log( window.typeOfBird ); // I'm a global variable too :(
-- JavaScript 会将忘记声明的变量(上typeOfBird)定义为全局变量
3> 明确向Window添加对象.
var type = "Red",
attack = function() {
typeOfBird = type + " Bird";
window.message = typeOfBird + " Attacks!";
return typeOfBird + " Bird Attacks!";
};
console.log( window.type ); // I'm a global variable
console.log( window.attack() ); // I'm a global function
console.log( window.typeOfBird ); // I'm a global variable too :(
console.log( window.message ); // I'm a global variable too :|
4> 为什么全局变量是个问题。
1、与你项目通组成员代码冲突。
2、与第三方库发生冲突。
3、与浏览器发生冲突。
5> 保护自己的多种方式.
1>、对象字面量
// Gather type & attack and make properties off higher level object
var bird = {
type: "Red",
attack: function() {
console.log( this.type + " Bird Attacks!" );
}
};
console.log( window.bird ); // Only 1 global object!
console.log( window.bird.type ); // Red
console.log( window.bird.attack() ); // Red Bird Attacks!
2>、立即调用的函数表达式 IIFE Immediately-invoked Function Expression
(function(){
}());
--------------------------------------
// Revealing Module Pattern
var bird = (function() {
var type = "Red",
power = "IIFE", // This is private
attack = function() {
console.log( type + " Bird Attacks with an " + power + "!" );
};
return { // Only the items returned are public
type: type,
attack: attack
};
}());
console.log( window.bird ); // Only 1 global object!
console.log( window.bird.type ); // Public property
console.log( window.bird.attack() ); // Public method accessing private var
console.log( window.bird.power ); // Private variable, can't access
---------------------------------------
(function( bird ) {
var power = "IIFE"; // This is private
bird.type = "Red";
bird.attack = function() {
console.log( bird.type + " Bird Attacks with an " + power + "!" );
};
}( window.bird = window.bird || {} ));
console.log( window.bird ); // Only 1 global object!
console.log( window.bird.type ); // Public property
console.log( window.bird.attack() ); // Public method accessing private var
console.log( window.bird.power ); // Private variable, can't access