JavaScript基礎知識(二)
一、JavaScript事件詳解
1、事件流:描述的是在頁面中結束事件的順序
事件傳遞有兩種方式:冒泡與捕獲。
事件傳遞定義了元素事件觸發的順序。 如果你將 <p> 元素插入到 <div> 元素中,用戶點擊 <p> 元素, 哪個元素的 "click" 事件先被觸發呢?
在 冒泡 中,內部元素的事件會先被觸發,然後再觸發外部元素,即: <p> 元素的點擊事件先觸發,然後會觸發 <div> 元素的點擊事件。
在 捕獲 中,外部元素的事件會先被觸發,然後才會觸發內部元素的事件,即: <div> 元素的點擊事件先觸發 ,然後再觸發 <p> 元素的點擊事件。
2、事件的處理:
①HTML事件處理:直接添加到HTML結構中
<body> <div id="div"> <button id="btn" onclick="demo()">按鈕</button> </div> <script> function demo() { alert("Hello html事件處理"); } </script> </body>
②DOMO級事件處理:把一個函數賦值給一個事件處理程序屬性
<body>
<div id="div">
<button id="btn1">按鈕</button>
</div>
<script>
var btn1 = document.getElementById("btn1");
btn1.onclick = function(){alert("Hello DOMO事件出現程序1")}//設置事件處理
btn1.onclick = function(){alert("Hello DOMO事件出現程序2")}//前一個被覆蓋
btn1.onclich = null;//移除事件處理
</script>
</body>
③DOM2級事件處理:
addEventListener("事件名","事件處理函數","布爾值");
true:事件捕獲
false:事件冒泡<body>
<div id="div">
<button id="btn1">按鈕</button>
</div>
<script>
var btn1 = document.getElementById("btn1");
btn1.addEventListener("click",demo1);//不會被覆蓋,依次執行
btn1.addEventListener("click",demo2);
function demo1(){
alert("Hello DOM2級事件出現程序1")
}
function demo2(){
alert("Hello DOM2級事件出現程序2")
}
btn1.removeEventListener("click",demo2);//移除事件2
</script>
</body>
removeEventListener();
④IE事件處理程序
attachEvent
datachEvent
1 <body>
2 <div id="div">
3 <button id="btn1">按鈕</button>
4 </div>
5 <script>
6 var btn1 = document.getElementById("btn1");
7 if(btn1.addEventListener){
8 btn1.addEventListener("click",demo);
9 }else if(btn1.attachEvent){
10 btn1.attachEvent("onclick",demo);
11 }else{
12 btn1.onclick = demo();
13 }
14 function demo(){
15 alert("Hello DOM2級事件出現程序2")
16 }
17 </script>
18 </body>
3、事件對象:在觸發DOM事件的時候都會產生一個對象
①事件對象event:
- type:獲取事件類型
- target:獲取事件目標
-
1 <body> 2 <div id="div"> 3 <button id="btn1">按鈕</button> 4 </div> 5 <script> 6 var btn1 = document.getElementById("btn1"); 7 btn1.addEventListener("click",show); 8 function show(event) { 9 alert(event.type);//獲取對象類型,如click 10 alert(event.target);//獲取事件目標,如[object HTMLButtonElement] 11 } 12 </script> 13 </body>
- stopPropagation():阻止事件冒泡
- preventDefault():阻止事件默認行為
-
1 <body> 2 <div id="div"> 3 <button id="btn1">按鈕</button> 4 <a id="aid" href="http://www.hao123.com">好123</a> 5 </div> 6 <script> 7 document.getElementById("btn1").addEventListener("click",showTarget); 8 document.getElementById("div").addEventListener("click",showDiv); 9 document.getElementById("aid").addEventListener("click",showA); 10 function showTarget(event) { 11 alert(event.target); 12 event.stopPropagation();//阻止事件冒泡,即點擊按鈕時,阻止事件傳遞到div(阻止觸發div) 13 } 14 function showDiv() { 15 alert("div") 16 } 17 function showA(event) { 18 event.stopPropagation();//跳轉,但阻止向上傳遞(阻止觸發div) 19 event.preventDefault();//阻止事件默認行為,如點擊鏈接時跳轉 20 } 21 </script> 22 </body>
二、JavaScript內置對象
1、對象
JavaScript 中的所有事物都是對象:字符串、數值、數組、函數...
每個對象帶有屬性和方法的特殊數據類型。
JavaScript 允許自定義對象
2、創建 JavaScript 對象
通過 JavaScript,您能夠定義並創建自己的對象。
創建新對象有兩種不同的方法:
- 定義並創建對象的實例
- 使用函數來定義對象,然後創建新的對象實例
-
<body> <!--創建對象--> <script> // 創建對象方式一 // people = new Object(); // people.name = "lilei"; // people.age = "15"; // people ={name:"lilei",age:"15"};//上三行可合並寫此方式 // document.write("name:"+people.name+" age:"+people.age); // 創建對象方式二 function people(name,age) { this.name=name;//this 指明對象 this.age = age; } son = new people("lilei",15); document.write("name:"+son.name+"age:"+son.age); </script> </body>
3、String字符串對象
字符串可以存儲一系列字符,如 "John Doe"。
字符串可以是插入到引號中的任何字符。你可以使用單引號或雙引號;
①字符串屬性
屬性 |
描述 |
---|---|
constructor | 返回創建字符串屬性的函數 |
length | 返回字符串的長度 |
prototype | 允許您向對象添加屬性和方法 |
②字符串常見方法
方法 | 描述 |
indexOf() | 返回字符串中檢索指定字符第一次出現的位置 |
lastIndexOf() | 返回字符串中檢索指定字符最後一次出現的位置 |
match() | 找到一個或多個正則表達式的匹配 |
replace() | 替換與正則表達式匹配的子串 |
toUpperCase() | 把字符串轉換為大寫 |
toLowerCase() | 把字符串轉換為小寫 |
split() | 把字符串分割為子字符串數組 |
charAt() | 返回指定索引位置的字符 |
charCodeAt() | 返回指定索引位置字符的 Unicode 值 |
concat() | 連接兩個或多個字符串,返回連接後的字符串 |
fromCharCode() | 將 Unicode 轉換為字符串 |
localeCompare() | 用本地特定的順序來比較兩個字符串 |
search() | 檢索與正則表達式相匹配的值 |
slice() | 提取字符串的片斷,並在新的字符串中返回被提取的部分 |
substr() | 從起始索引號提取字符串中指定數目的字符 |
substring() | 提取字符串中兩個指定的索引號之間的字符 |
toString() | 返回字符串對象值 |
trim() | 移除字符串首尾空白 |
valueOf() | 返回某個字符串對象的原始值 |
4、Date 對象
Date 對象用於處理日期與實際。
①Date 對象屬性
屬性 |
描述 |
---|---|
constructor | 返回對創建此對象的 Date 函數的引用。 |
prototype | 使您有能力向對象添加屬性和方法。 |
②常用方法:
-
- Date() :獲得當前的時間。
- getFullYear():使用 getFullYear() 獲取年份。
- getTime():getTime() 返回從 1970 年 1 月 1 日至今的毫秒數。
- setFullYear():如何使用 setFullYear() 設置具體的日期。
- toUTCString():如何使用 toUTCString() 將當日的日期(根據 UTC)轉換為字符串。
- getDay():如何使用 getDay() 和數組來顯示星期,而不僅僅是數字。
- Display a clock:如何在網頁上顯示一個鐘表。
-
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>菜鳥教程(runoob.com)</title> 6 <script> 7 function startTime(){ 8 var today=new Date(); 9 var h=today.getHours(); 10 var m=today.getMinutes(); 11 var s=today.getSeconds();// 在小於10的數字前加一個‘0’ 12 m=checkTime(m); 13 s=checkTime(s);
document.getElementById(‘txt‘).innerHTML=h+":"+m+":"+s; 14 t=setTimeout(function(){startTime()},500); 15 } 16 function checkTime(i){ 17 if (i<10){ 18 i="0" + i; 19 } 20 return i; 21 } 22 </script> 23 </head> 24 <body onload="startTime()"> 25 <div id="txt"></div> 26 </body> 27 </html>
5、 Array(數組) 對象
數組對象是使用單獨的變量名來存儲一系列的值。
①創建數組方法:
- 常規方式:
var myCars=new Array(); myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW";
- 簡潔方式:var myCars=new Array("Saab","Volvo","BMW");
- 字面:var myCars=["Saab","Volvo","BMW"];
②數組的屬性
屬性 | 描述 |
---|---|
constructor | 返回創建數組對象的原型函數。 |
length | 設置或返回數組元素的個數。 |
prototype | 允許你向數組對象添加屬性或方法。 |
③常用方法
方法 | 描述 |
concat() | 連接兩個或更多的數組,並返回結果。 |
sort() | 對數組的元素進行排序。 |
push() | 向數組的末尾添加一個或更多元素,並返回新的長度。 |
reverse() | 反轉數組的元素順序。 |
//升序排列
var points = [40,100,1,5,25,10];
points.sort(function(a,b){return a-b});
//降序排列
var points = [40,100,1,5,25,10];
points.sort(function(a,b){return b-a});
6、Math對象
Math 對象用於執行數學任務。
使用Math的屬性/方法的語法:
var x=Math.PI;
var y=Math.sqrt(16);
round():如何使用 round()。
random():使用 random() 來返回 0 到 1 之間的隨機數。使用parstInt(Math.random()*10)產生0-10間的隨機整數。
max(): max() 來返回兩個給定的數中的較大的數。
min():使用 min() 來返回兩個給定的數中的較小的數。
三、JavaScript DOM對象控制HTML元素詳解
在 HTML DOM 中,所有事物都是節點。DOM 是被視為節點樹的 HTML。
1、常用方法:
方法 | 描述 |
getElementById() | 返回帶有指定 ID 的元素。 |
getElementsByTagName() | 返回包含帶有指定標簽名稱的所有元素的節點列表(集合/節點數組)。 |
getElementsByName() | 返回包含帶有指定name名稱的所有元素的節點列表(集合/節點數組)。 |
getElementsByClassName() | 返回包含帶有指定類名的所有元素的節點列表。 |
appendChild() | 把新的子節點添加到指定節點。 |
childNodes() | 訪問子節點 |
parentNode() | 訪問父節點 |
removeChild() | 刪除子節點。 |
replaceChild() | 替換子節點。 |
insertBefore() | 在指定的子節點前面插入新的子節點。 |
createAttribute() | 創建屬性節點。 |
createElement() | 創建元素節點。 |
createTextNode() | 創建文本節點。 |
getAttribute() | 返回指定的屬性值。 |
setAttribute() | 把指定屬性設置或修改為指定的值。 |
offsetHeight | 返回,任何一個元素的高度包括邊框和填充,但不是邊距 |
scrollHeight | 返回整個元素的高度(包括帶滾動條的隱蔽的地方) |
示例:
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Title</title>
6 </head>
7 <body>
8 <p name="pn">Hello</p>
9 <p name="pn">Hello</p>
10 <p name="pn">Hello</p>
11 <p name="pn">Hello</p>
12 <a id="aid" title="得到了a標簽的屬性"></a>
13 <a id="aid2"></a>
14 <ul><li>1</li><li>2</li><li>3</li></ul>
15 <div id="div">
16 <p id="pid">div的p元素</p>
17 </div>
18 <script>
19 //獲取元素
20 function getName() {
21 var count = document.getElementsByName("pn");//以name方式獲取獲取該類集合
22 //var count = document.getElementsByTagName("p");//以元素名獲取集合
23 alert(count.length);
24 var p = count[2];
25 p.innerHTML = "World";
26 }
27 //獲取節點屬性
28 function getAttr() {
29 var anode = document.getElementById("aid");
30 var attr = anode.getAttribute("title");
31 alert(attr);
32 }
33 //設置節點屬性
34 function setAttr() {
35 var anode = document.getElementById("aid2");
36 anode.setAttribute("title","動態標簽title屬性");
37 var attr = anode.getAttribute("title");
38 alert(attr);
39 }
40 //獲取子節點
41 function getChildNode() {
42 var childnode = document.getElementsByTagName("ul")[0].childNodes;
43 alert(childnode.length);
44 alert(childnode[0].nodeType);
45 }
46 //獲取父節點
47 function getParentNode() {
48 var div = document.getElementById("pid");
49 alert(div.parentNode.nodeName);
50 }
51 //創建節點
52 function createNode() {
53 var body = document.body;
54 var input = document.createElement("input");
55 input.type="button";
56 input.value="按鈕";
57 body.appendChild(input);//添加節點到body末尾
58 }
59 //指定位置添加節點
60 function addNode() {
61 var div = document.getElementById("div");
62 var node = document.getElementById("pid");
63 var newnode = document.createElement("p");
64 newnode.innerHTML = "動態添加一個p元素";
65 div.insertBefore(newnode,node);
66 }
67 //刪除節點
68 function removeNode() {
69 var div = document.getElementById("div");
70 var p = div.removeChild(div.childNodes[1]);
71 }
72 //獲取頁面尺寸
73 function getSize() {
74 var width = document.body.offsetWidth || document.documentElement.offsetWidth;
75 //前半句兼容性較好
76 var height = document.documentElement.offsetHeight;
77 alert(width+","+height);
78 }
79 getSize();
80 </script>
81 </body>
82 </html>
四、JavaScript瀏覽器對象
1、window對象
①window對象
-
- 所有瀏覽器都支持 window 對象。它表示瀏覽器窗口。
- 所有 JavaScript 全局對象、函數以及變量均自動成為 window 對象的成員。
- 全局變量是 window 對象的屬性。
- 全局函數是 window 對象的方法。
- 甚至 HTML DOM 的 document 也是 window 對象的屬性之一
②Window 尺寸
有三種方法能夠確定瀏覽器窗口的尺寸。
對於Internet Explorer、Chrome、Firefox、Opera 以及 Safari:
-
- window.innerHeight - 瀏覽器窗口的內部高度(包括滾動條)
- window.innerWidth - 瀏覽器窗口的內部寬度(包括滾動條)
對於 Internet Explorer 8、7、6、5:
-
- document.documentElement.clientHeight
- document.documentElement.clientWidth
或者
-
- document.body.clientHeight
- document.body.clientWidth
③其他 Window 方法
-
- window.open() - 打開新窗口
- window.close() - 關閉當前窗口
- window.moveTo() - 移動當前窗口
- window.resizeTo() - 調整當前窗口的尺寸
1 <body>
2 <button id="btn" onclick="btnClicked()">按鈕</button>
3 <script>
4 //打印窗口的高度和寬度
5 // document.write("寬度:"+window.innerWidth+",高度:"+window.innerHeight);
6 function btnClicked() {
7 //打開一個新的窗口(第二、三個參數為可選項),並可設置窗口屬性,第三個參數可根據需要設置新窗口的一些屬性
8 //window.open("obindex.html","windowname","height = 200,width=200,top=100,left=100");
9 //關閉窗口
10 window.close();
11 }
12 </script>
13 </body>
2、JavaScript 計時事件
①計時事件
通過使用 JavaScript,我們有能力作到在一個設定的時間間隔之後來執行代碼,而不是在函數被調用後立即執行。我們稱之為計時事件。
②計時方法
-
- setInterval() - 間隔指定的毫秒數不停地執行指定的代碼。
window.setInterval("javascript function",milliseconds);
clearInterval() 方法用於停止 setInterval() 方法執行的函數代碼。
window.clearInterval(intervalVariable)
1 <body>
2 <button id="btn" onclick="stopTime()">按鈕</button>
3 <p id="ptime"></p>
4 <script>
5 var mytime = setInterval(function () {
6 getTime();
7 },1000);
8 function getTime() {
9 var d = new Date();
10 var t = d.toLocaleTimeString();
11 document.getElementById("ptime").innerHTML=t;
12 }
13 function stopTime() {
14 //停止執行
15 clearInterval(mytime);
16 }
17 </script>
18 </body>
-
- setTimeout() - 暫停指定的毫秒數後執行指定的代碼
window.setTimeout("javascript 函數",毫秒數);
clearTimeout() 方法用於停止執行setTimeout()方法的函數代碼。
window.clearTimeout(timeoutVariable)
1 <body onload="myWin()">
2 <button id="btn" onclick="stopWin()">按鈕</button>
3 <script>
4 var win;
5 function myWin(){
6 alert("hello")
7 //延遲3秒彈出,自調自,形成死循環
8 win = setTimeout(function(){myWin()},3000);
9 }
10 //停止執行
11 function stopWin() {
12 clearTimeout(win);
13 }
14 </script>
15 </body>
Note: setInterval() 和 setTimeout() 是 HTML DOM Window對象的兩個方法,調用時可直接寫該方法,省略window
3、History對象
①History對象
window.history 對象包含瀏覽器的歷史(url)的集合。
②History方法:
- history.back() - 與在瀏覽器點擊後退按鈕相同,加載歷史列表中的前一個 URL。
-
1 <html> 2 <head> 3 <script> 4 function goBack(){ 5 window.history.back() 6 } 7 </script> 8 </head> 9 <body> 10 <input type="button" value="Back" onclick="goBack()"> 11 </body> 12 </html>
- history.forward() - 與在瀏覽器中點擊按鈕向前相同
- history.go() - 進入歷史中的某個頁面
-
模擬跳轉到登錄界面再返回原先界面
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <a href="obindex.html">跳轉</a> 9 </body> 10 </html>//obindex.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <script> 7 function safe() { 8 var name = document.getElementById("username").value; 9 if (name=="hello"){ 10 // 跳轉到前一個頁面 11 history.go(-1); 12 }else{ 13 alert("輸入錯誤"); 14 } 15 } 16 </script> 17 </head> 18 <body> 19 <form> 20 <input type="text" id="username"> 21 <button id="btn" onclick="safe()">按鈕</button> 22 </form> 23 </body> 24 </html>
4、JavaScript Window Location
window.location 對象用於獲得當前頁面的地址 (URL),並把瀏覽器重定向到新的頁面。
Location對象的屬性:
-
- location.hostname 返回 web 主機的域名
- location.pathname 返回當前頁面的路徑和文件名
- location.port 返回 web 主機的端口 (80 或 443)
- location.protocol 返回所使用的 web 協議(http:// 或 https://)
- location.href 屬性返回當前頁面的 URL。
- location.assign() 方法加載新的文檔。
<script>
document.write(location.pathname);
</script>
window.location.assign("http://www.w3cschool.cc")
5、JavaScript Window Screen
window.screen 對象包含有關用戶屏幕的信息。
一些屬性:
- screen.availWidth - 可用的屏幕寬度
-
<script> document.write("可用寬度: " + screen.availWidth); </script>
- screen.availHeight - 可用的屏幕高度
- screen.width-屏幕寬度
- screen.height -屏幕高度
五、面向對象
- 一切事物皆對象
- 對象具有封裝和繼承特性
- 對象與對象之間使用消息通信,各自存在信息隱藏
1、對象的創建
①創建一個沒有任何屬性的對象:
var obj = {};
②創建一個對象並設置屬性及初始值:
var person = {name:"Angel",age:18,married:false};
③創建一個對象並設置屬性和方法:
var speaker = {text:"Hello World",say:function(){aler(this.text)}};
④創建一個復雜的對象,嵌套其他對象和對象數組等:
var company =
{ name: "Microsoft", product: "softwares", chairman: {name: "Bill Gates", age: 53, Married: true}, employees: [{name: "Angel", age: 26, Married: false}, {name: "Hanson", age: 32, Marred: true}], readme: function() {document.write(this.name + " product " + this.product);} };
2、對象的另外一種創建方法(函數構造器)
使用new操作符結合一個函數的形式來創建對象。
function MyFunc() {}; //定義一個空函數 var anObj = new MyFunc(); //使用new操作符,借助MyFun函數,就創建了一個對象
上述創建方法等價於:
function MyFunc(){};
var anObj = {}; //創建一個對象
MyFunc.call(anObj); //將anObj對象作為this指針調用MyFunc函數
繼承的體現:
1 function Person(name) { //帶參數的構造函數
2 this.name = name; //將參數值賦給給this對象的屬性
3 this.SayHello = function() {alert("Hello, I‘m " + this.name);}; //給this對象定義一個SayHello方法。
4 };
5
6 function Employee(name, salary){ //子構造函數
7 Person.call(this, name); //將this傳給父構造函數
8 this.salary = salary; //設置一個this的salary屬性
9 this.ShowMeTheMoney = function() {alert(this.name + " $" + this.salary);}; //添加ShowMeTheMoney方法。
10 };
11
12 var BillGates = new Person("Bill Gates"); //用Person構造函數創建BillGates對象
13 var SteveJobs = new Employee("Steve Jobs", 1234); //用Empolyee構造函數創建SteveJobs對象
14
15 BillGates.SayHello(); //顯示:I‘m Bill Gates
16 SteveJobs.SayHello(); //顯示:I‘m Steve Jobs
17 SteveJobs.ShowMeTheMoney(); //顯示:Steve Jobs $1234
18
19 alert(BillGates.constructor == Person); //顯示:true
20 alert(SteveJobs.constructor == Employee); //顯示:true
21
22 alert(BillGates.SayHello == SteveJobs.SayHello); //顯示:false
這段代碼表明,函數不但可以當作構造函數,而且還可以帶參數,還可以為對象添加成員和方法。其中的第9行,Employee構造函數又將自己接收的 this作為參數調用Person構造函數,這就是相當於調用基類的構造函數。第21、22行還表明這樣一個意思:BillGates是由Person構造的,而SteveJobs是由Employee構造的。對象內置的constructor屬性還指明了構造對象所用的具體函數!
3、原型
① JavaScript的所有function類型的對象都有一個prototype屬性。這個prototype屬性本身又是一個object類型的對 象,因此我們也可以給這個prototype對象添加任意的屬性和方法。既然prototype是對象的“原型”,那麽由該函數構造出來的對象應該都會具 有這個“原型”的特性。事實上,在構造函數的prototype上定義的所有屬性和方法,都是可以通過其構造的對象直接訪問和調用的。也可以這麽 說,prototype提供了一群同類對象共享屬性和方法的機制。(類似於Java 中的繼承)
function Person(name){
this.name = name; //設置對象屬性,每個對象各自一份屬性數據
};
Person.prototype.SayHello = function(){ //給Person函數的prototype添加SayHello方法。
alert("Hello, I‘m " + this.name);
}
var BillGates = new Person("Bill Gates"); //創建BillGates對象
var SteveJobs = new Person("Steve Jobs"); //創建SteveJobs對象
BillGates.SayHello(); //通過BillGates對象直接調用到SayHello方法
SteveJobs.SayHello(); //通過SteveJobs對象直接調用到SayHello方法
alert(BillGates.SayHello == SteveJobs.SayHello); //因為兩個對象是共享prototype的SayHello,所以顯示:true
程序運行的結果表明,構造函數的prototype上定義的方法確實可以通過對象直接調用到,而且代碼是共享的。
②用這簡單的掩蓋機制實現了對象的“多態”性(類似於Java中的overrid):
function Person(name){
this.name = name;
};
Person.prototype.company = "Microsoft"; //原型的屬性
Person.prototype.SayHello = function(){ //原型的方法
alert("Hello, I‘m " + this.name + " of " + this.company);
};
var BillGates = new Person("Bill Gates");
BillGates.SayHello(); //由於繼承了原型的東西,規規矩矩輸出:Hello, I‘m Bill Gates
var SteveJobs = new Person("Steve Jobs");
SteveJobs.company = "Apple"; //設置自己的company屬性,掩蓋了原型的company屬性
SteveJobs.SayHello = function(){ //實現了自己的SayHello方法,掩蓋了原型的SayHello方法
alert("Hi, " + this.name + " like " + this.company + ", ha ha ha ");
};
SteveJobs.SayHello(); //都是自己覆蓋的屬性和方法,輸出:Hi, Steve Jobs like Apple, ha ha ha
BillGates.SayHello(); //SteveJobs的覆蓋沒有影響原型對象,BillGates還是按老樣子輸出
③動態擴展性
function Person(name){
this.name = name;
};
Person.prototype.SayHello = function(){ //建立對象前定義的方法
alert("Hello, I‘m " + this.name);
};
var BillGates = new Person("Bill Gates"); //建立對象
BillGates.SayHello();
Person.prototype.Retire = function(){ //建立對象後再動態擴展原型的方法
alert("Poor " + this.name + ", bye bye!");
};
BillGates.Retire(); //動態擴展的方法即可被先前建立的對象立即調用
④信息的隱藏(類似於Java中的封裝)
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title>菜鳥教程(runoob.com)</title>
6 </head>
7 <body>
8
9 <p>局部變量計數。</p>
10 <button type="button" onclick="myFunction()">計數!</button>
11 <p id="demo">0</p>
12 <script>
13 var add = (function () {
14 var counter = 0;
15 return function () {return counter += 1;}
16 })();
17 function myFunction(){
18 document.getElementById("demo").innerHTML = add();
19 }
20 </script>
21 </body>
22 </html>
⑤原型模型大致寫法
//定義構造函數
function Person(name){
this.name = name; //在構造函數中定義成員
};
//方法定義到構造函數的prototype上
Person.prototype.SayHello = function(){
alert("Hello, I‘m " + this.name);
};
//子類構造函數
function Employee(name, salary){
Person.call(this, name); //調用上層構造函數
this.salary = salary; //擴展的成員
};
//子類構造函數首先需要用上層構造函數來建立prototype對象,實現繼承的概念
Employee.prototype = new Person() //只需要其prototype的方法,此對象的成員沒有任何意義!
//子類方法也定義到構造函數之上
Employee.prototype.ShowMeTheMoney = function(){
alert(this.name + " $" + this.salary);
};
var BillGates = new Person("Bill Gates");
BillGates.SayHello();
var SteveJobs = new Employee("Steve Jobs", 1234);
SteveJobs.SayHello();
SteveJobs.ShowMeTheMoney();
JavaScript基礎知識(二)