5 js物件導向的思想--閉包,圓形,物件
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
//三種變數 三種方法
function Person1(){
var name="wiki";
this.name2 = "wiki2";
function m1(){
alert("m1");
}
this.m2=function(){
alert("m2");
m1();
};
}
Person1.ourname="wiki3";
Person1.m3=function(){
alert("m3");
}
var p = new Person1();
/* alert(p.name);
alert(p.name2);
alert(Person1.ourname); */
/*p.m1();*/
/* p.m2();
Person1.m3(); */
//動態新增刪除物件
p.v1="v1";
p.v2=function(){
alert("v2");
};
/* alert(p.v1);
p.v2();
delete p.v1;
delete p.v2;
alert(p.v1);
p.v2();//沒有回出錯 */
//this動態指向 --this指定什麼就算什麼
var names = "wiki";
function say(){
alert(this.names);
}
var car = {names:"hello",say:say};
/* say();
car.say();
car.say.apply(window); */
//圓形問題
function Person2(){};
var p2 = new Person2();
/* alert(Person2.prototype);
alert(Person2.prototype.constructor);
alert(p2.prototype); */
//原型繼承例項
function Person3(name){
this.name=name;
this.say=function(){
return this.name;
};
};
function Child(){
}
Child.prototype=new Person3("i am a person");
var child = new Child();
alert(child.say());
//閉包例項 +方法加方法必須返回裡面的方法名,否則語法錯誤
//閉包使得變數永久儲存於記憶體中
function Person4(){
var n=998;
function getN(){
n++;
alert(n);
};
function getM(){
alert(n+"11");
};
return getN;
}
var result = Person4();
result();
result();
</script>
</head>
<body>
</body>
</html>