• 我们应该有新到生活,为我们未经生活过到的。

面向对象的一些知识归纳


//闭包允许你引用父函数中的变量,但是提供的值并非该变量创建时候的值
//而是在父函数范围内的最终值。
(function(){
	var demo=document.getElementById("main");
	var items=["click","mouseover","mouseout"];
	for(var i=0;i < items.length;i++){
		(function(){
			var item=items[i];//这样也能绑定事件函数?
			demo["on"+item]=function(){
				alert("tanks for youe"+item);
			}
		})();
	}
})();
//////////////////////////////////////////////////////////
(function(){
	var demo=document.getElementById("main");
	demo.style.border="1px solid red";
	setTimeout(function(){demo.style.background="red"},2000);
})();//自执行的匿名函数:这样做就是避免了大量的全局函数,全局变量

//闭包--即使外层函数的执行已经终止,内层函数可以引用存在于包围它的函数内的变量;
function delaMes(mes,time){
	setTimeout(	function(){alert(mes)},time	)
}
delaMes("2秒之后是不是DEMO的颜色变红了?",5000);

//A simple JavaScript closure
(function() {
	var ourFunction2 = function() { alert(ourVar); };
	var ourVar = "A simple JavaScript closure";
	ourFunction2();
})()
/////////////////////////////////////////////////////
//上下文对象:代码处在该对象之内。用THIS变量来体现
//这个变量永远指向当前代码所处的对象中
var obj={
	yes:function(){
		this.val=true;
	},
	no:function(){
		this.val=false;
	}
};
//用一下方法验证了,obj此时还没有VAL属性
alert(obj.val); //undefine
obj.yes();
alert(obj.val); //true
window.no=obj.no;//window.no指向obj.no
//obj对象的VAL不变,因为no的上下文已经改变为window对象了
window.no();
alert(obj.val);//true
alert(window.val)//false
//////////////////////////////////////////////////////////
//对象
function user(name){
	this.name = name;
	this.sayWhat=function (){
		alert("my name is:"+this.name);
	}
	//创建私有方法,之能对象内部访问,外面不能调用
	function sayHi(){
		alert("i am a private mothod")
	};
	sayHi();
}
var man=new user("man name");
//man.sayHi();会报错!
user.prototype.age=22;
var woman =new man.constructor("women name");
alert(man.constructor==woman.constructor);
//constructor属性在每个对象中都存在,并一直指向创建它的函数。
woman.sayWhat();
//prototype原型(也是一个对象)为对象添加方法。
alert(woman.age);

window.foo="test";
if(true){
	var foo="new test";
}
function change(){
	var foo="old test";
}
change();
alert(foo);//new test