1、立即调用的函数表达式:

	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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值