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、立即調用的函數表達式:
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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.