JavaScript學習筆記(三)——對象

第四章 理解對象

1 說明

  對象的狀態:屬性,行爲:方法;

  對象定義放在花括號內;

  用冒號分隔屬性名和屬性值;

  用逗號分隔屬性名和屬性值對,包括方法;

  最後一個屬性值後面不加逗號;

  屬性名可以是任何字符串,但通常遵循變量命名規則,包含空格時必須用引號將其括起來;

  同一個對象中不能包含兩個同名的屬性;

  句點表示法訪問對象,當然也可以用方括號方法(更爲靈活且需注意無逗號);

  添加新屬性:指定新屬性並賦值:fiat.needsWashing=true;

  刪除屬性:delete fido.dogYears;(刪除成功返回true);

  創建一個無屬性的對象: var lookMaNoProps={ };

  將對象信息顯示到控制檯: console.log(fiat);

  函數中傳遞的是對象的引用,因此在函數中對對象的修改有效;

2 實例1:

 1 <script language="JavaScript" type="text/JavaScript">
 2 function getSecret(file,secretPassword)
 3 {
 4 file.opened=file.opened+1;
 5 if(secretPassword==file.password)
 6 return file.contents;
 7 else
 8 return "Invalid password! No secret for you.";
 9 }
10 function setScret(file,secretPassword,secret)
11 {
12 if(secretPassword==file.password)
13 {
14 file.opened=0;
15 file.contents=secret;
16 }
17 }
18 var superSecretFile={
19 level:"classifiled",
20 opened:0,
21 password:2168,
22 contents: "Dr. Evel's next meeting is in Detroit."
23 };
24 var secret=getSecret(superSecretFile,2168);
25 console.log(secret);
26 var secret1=getSecret(superSecretFile,2152);
27 console.log(secret1);
28 setScret(superSecretFile,2168,"Dr . Evel's next meeting is in Philadelphia");
29 secret=getSecret(superSecretFile,2168);
30 console.log(secret);
31 </script>

 

3 實例2:

  1 <!doctype html>
  2 
  3 <html lang="en">
  4 
  5 <head>
  6 
  7 <title>Battleship</title>
  8 
  9 <meta charset="utf-8">
 10 
 11 </head>
 12 
 13 <body>
 14 
 15 <script language="JavaScript" type="text/JavaScript">
 16 
 17 function makeCar()
 18 
 19 {
 20 
 21 var makes=["Chevy","GM","Fiat","Webville Motors","Tucker"];
 22 
 23 var models=["Cadillac","500","Bel-Air","Taxi","Torpedo"];
 24 
 25 var years=[1955,1957,1948,1954,1961];
 26 
 27 var colors=["red","blue","tan","yellow","white"];
 28 
 29 var convertile=[true,false];
 30 
 31  
 32 
 33 var rand1=Math.floor(Math.random()*makes.length);
 34 
 35 var rand2=Math.floor(Math.random()*models.length);
 36 
 37 var rand3=Math.floor(Math.random()*years.length);
 38 
 39 var rand4=Math.floor(Math.random()*colors.length);
 40 
 41 var rand5=Math.floor(Math.random()*5)+1;
 42 
 43 var rand6=Math.floor(Math.random()*2);
 44 
 45  
 46 
 47 var car={
 48 
 49 make:makes[rand1],
 50 
 51 model:models[rand2],
 52 
 53 year:years[rand3],
 54 
 55 color:colors[rand4],
 56 
 57 passengers:rand5,
 58 
 59 convertile:convertile[rand6],
 60 
 61 mileage:0,
 62 
 63 fuel:0,
 64 
 65 started:false,
 66 
 67  
 68 
 69 start:function(){
 70 
 71 this.started=true;
 72 
 73 },
 74 
 75 stop:function(){
 76 
 77 this.started=false;
 78 
 79 },
 80 
 81 drive:function(){
 82 
 83 if(this.started)
 84 
 85 {
 86 
 87 if(this.fuel>0)
 88 
 89 alert("Zoom zoom!");
 90 
 91 else
 92 
 93 {
 94 
 95 alert("Uh , oh ,out of fuel!");
 96 
 97 this.stop();
 98 
 99 }
100 
101 }
102 
103 else
104 
105 alert("You need to start the engine first!");
106 
107 },
108 
109 addFuel:function(amount){
110 
111 this.fuel+=amount;
112 
113 }
114 
115 };
116 
117 return car;
118 
119 }
120 
121 function displayCar(car)
122 
123 {
124 
125 console.log("Your new car is a "+car.year+" "+car.make+" "+car.model);
126 
127 }        
128 
129 var Cadillac=makeCar();
130 
131 displayCar(Cadillac);
132 
133 //訪問對象中的屬性
134 
135 //方法一:迭代器
136 
137 for(var pup in Cadillac)
138 
139 {
140 
141 console.log(pup+" : "+        Cadillac[pup]);
142 
143 }
144 
145 //方法二:句點訪問法和方括號訪問法
146 
147 console.log("You new car 's color is "+Cadillac.color);
148 
149 console.log("Your car counld hold "+Cadillac["passengers"]+" people.");
150 
151 console.log("Your car counld hold "+Cadillac["passe"+"ngers"]+" people.");
152 
153  
154 
155 Cadillac.drive();//開車
156 
157 Cadillac.start();//啓動
158 
159 Cadillac.drive();//開車
160 
161 Cadillac.addFuel(15);//加油
162 
163 Cadillac.start();//啓動
164 
165 Cadillac.drive();//開車
166 
167 Cadillac.stop();//熄火
168 
169 Cadillac.drive();//開車
170 
171 </script>
172 
173 </body>
174 </html>


 

4 對象拓展

  JavaScript提供:

  Date, Math, RegExp(字符串中查找), JSON(與其他應用程序交換js對象)

  瀏覽器提供:

  Doucument(寫入網頁),Windows(,與瀏覽器相關),Console(與控制檯相關)

 

五、高級對象構造技巧

1 構造函數創建對象(模板)

  • 構造函數只能返回this;否則會導致函數不返回它創建的對象;
  • 判斷某個實例是否由某個構造函數創建;
  • cadi instanceof Dog;是返回true;
  • 當然可以使用上面闡述的方式更改對象的屬性和方法,更改後,intanceof依然顯示true;
 1 <!doctype html>
 2 
 3 <html lang="en">
 4 
 5 <head>
 6 
 7 <title>Dog wang!</title>
 8 
 9 <meta charset="utf-8">
10 
11 <style type="text/css">
12 
13  
14 
15 </style>
16 
17 <script language="JavaScript" type="text/JavaScript">
18 
19 //構造函數
20 
21 function Dog(name,breed,weight){
22 
23 this.name=name;
24 
25 this.breed=breed;
26 
27 this.weight=weight;
28 
29 this.bark=function(){
30 
31 if(this.weight>25)
32 
33 alert(this.name+" says Woof!");
34 
35 else
36 
37 alert(this.name+" says Yip!");
38 
39 };
40 
41 }
42 
43  
44 
45 var fido = new Dog("Fido", "Mixed", 38);
46 
47 var fluffy = new Dog("Fluffy", "Poodle", 30);
48 
49 var spot = new Dog("Spot", "Chihuahua", 10);
50 
51 var dogs = [fido, fluffy, spot];
52 
53  
54 
55 for(var i = 0; i < dogs.length; i++) {
56 
57 var size = "small";
58 
59 if (dogs[i].weight > 10) {
60 
61 size = "large";
62 
63 }
64 
65 console.log("Dog: " + dogs[i].name
66 
67 + " is a " + size
68 
69 + " " + dogs[i].breed
70 
71 );
72 
73 }
74 
75  
76 
77 for (var i = 0; i < dogs.length; i++) {
78 
79 dogs[i].bark();
80 
81 }
82 
83 </script>
84 
85 </head>
86 
87 <body>
88 
89  
90 
91 </body>
92 
93 </html>

 

2 內置構造函數

 1 var now=new Date();
 2 
 3 var dateString=now.toString();
 4 
 5 var year=now.getFullYear();
 6 
 7 var birthday=new Date("May 1,1998 08:09 pm");
 8 
 9 console.log(birthday.toString());
10 
11 console.log(dateString);
12 
13 console.log(year);

 

3 數組對象

var items=new Array("a","b","c");

console.log(items[2]);

4 其他內置對象

Object【對象字面量是其實例】,Math,RegExp,Error

5 使用原型創建對象

  • 在所使用上述構造函數創建對象時,每個不同的對象都需要分配內存(主要是行爲),爲了節約內存管理提出了繼承原型的方式創建對象,實質也是繼承對象;
  • Dog.prototype訪問原型
  • 原理:所有方法和屬性都是先在實例對象中查找調用,如果不存在則返回原型查找調用並將原型的屬性方法添加給實例對象;
  • spot.hasOwnProperty("sitting")可以測試sitting屬性是否在實例對象spot中存在,存在返回true否則false;
  • 學會創建原型鏈對象,最初始的都是Object對象
  • 例:
  1 <!doctype html>
  2 
  3 <html lang="en">
  4 
  5 <head>
  6 
  7 <meta charset="utf-8">
  8 
  9 <title>Show dogs</title>
 10 
 11 <script>
 12 
 13 //創建狗狗的原型
 14 
 15 function Dog(name, breed, weight) {
 16 
 17     this.name = name;
 18 
 19     this.breed = breed;
 20 
 21     this.weight = weight;
 22 
 23 }
 24 
 25 //爲狗狗添加屬性
 26 
 27 Dog.prototype.species = "Canine";
 28 
 29 Dog.prototype.sitting = false;
 30 
 31 //爲狗狗添加方法
 32 
 33 Dog.prototype.sit = function() {
 34 
 35 if (this.sitting) {
 36 
 37 console.log(this.name + " is already sitting");
 38 
 39 } else {
 40 
 41 console.log(this.name + " is now sitting");
 42 
 43 this.sitting = true;
 44 
 45 }
 46 
 47 }
 48 
 49 Dog.prototype.bark = function() {
 50 
 51 if (this.weight > 25) {
 52 
 53 console.log(this.name + " says Woof!");
 54 
 55 } else {
 56 
 57 console.log(this.name + " says Yip!");
 58 
 59 }
 60 
 61 };
 62 
 63 Dog.prototype.run = function() {
 64 
 65     console.log("Run!");
 66 
 67 };
 68 
 69 Dog.prototype.wag = function() {
 70 
 71     console.log("Wag!");
 72 
 73 };
 74 
 75 //創建一個表演狗的原型——構造函數
 76 
 77 /*
 78 
 79 function ShowDog(name, breed, weight, handler) {
 80 
 81 this.name = name;
 82 
 83 this.breed = breed;
 84 
 85 this.weight = weight;
 86 
 87 this.handler = handler;
 88 
 89 }
 90 
 91 */
 92 
 93 //改進版
 94 
 95 function ShowDog(name,breed,weight,handler)
 96 
 97 {
 98 
 99 Dog.call(this,name,breed,weight);//重用構造函數Dog中處理name等的代碼
100 
101 this.handler=handler;
102 
103 }
104 
105 //使表演狗原型繼承自狗狗原型
106 
107 ShowDog.prototype = new Dog();
108 
109 //重寫ShowDog的constructor屬性
110 
111 ShowDog.prototype.constructor=ShowDog;
112 
113 //爲表演狗原型添加新屬性
114 
115 ShowDog.prototype.league = "Webville";
116 
117 //爲表演狗原型添加方法
118 
119 ShowDog.prototype.stack = function() {
120 
121 console.log("Stack");
122 
123 };
124 
125  
126 
127 ShowDog.prototype.bait = function() {
128 
129 console.log("Bait");
130 
131 };
132 
133  
134 
135 ShowDog.prototype.gait = function(kind) {
136 
137 console.log(kind + "ing");
138 
139 };
140 
141  
142 
143 ShowDog.prototype.groom = function() {
144 
145 console.log("Groom");
146 
147 };
148 
149  
150 
151 //創建狗狗原型的實例對象
152 
153 var fido = new Dog("Fido", "Mixed", 38);
154 
155 var fluffy = new Dog("Fluffy", "Poodle", 30);
156 
157 var spot = new Dog("Spot", "Chihuahua", 10);
158 
159 //重寫spot實例的bark方法
160 
161 spot.bark = function() {
162 
163 console.log(this.name + " says WOOF!");
164 
165 };
166 
167 //創建表演狗原型的實例對象
168 
169 var scotty = new ShowDog("Scotty", "Scottish Terrier", 15, "Cookie");
170 
171 var beatrice = new ShowDog("Beatrice", "Pomeranian", 5, "Hamilton");
172 
173 //測試狗狗原型實例對象的方法調用
174 
175 fido.bark();
176 
177 fluffy.bark();
178 
179 spot.bark();
180 
181 //測試表演狗原型實例對象的方法調用
182 
183 scotty.bark();
184 
185 beatrice.bark();
186 
187  
188 
189 scotty.gait("Walk");
190 
191 beatrice.groom();
192 
193 //測試實例的constructor屬性
194 
195 console.log("FIdo constructor is "+fido.constructor);
196 
197 console.log("Scotty constructor is "+scotty.constructor);
198 
199 </script>
200 
201 </head>
202 
203 <body>
204 
205 </body>
206 
207 </html>

 

  • 重寫內置行爲
    • 如:重寫Object的toString()方法
    • 不可重寫屬性:

constructor 指向與這個原型相關聯的構造函數

hasOwnProperty判斷實例中是否實例化

isPrototypeOf 判斷一個對象是否是另一個對象的原型

propertyIsEnumerable 判斷通過迭代對象的所有屬性是否可訪問指定屬性

  • 可重寫:

toString 轉換爲字符串

toLocaleString 將對象轉換爲字符串,通過重寫可以描述對象的本地化字符串

valueOf 默認返回當前對象,通過重寫讓它返回你希望的其他值;

 

 1 <script>
 2 
 3 function Robot(name,year,owner)
 4 
 5 {
 6 
 7 this.name=name;
 8 
 9 this.year=year;
10 
11 this.owner=owner;
12 
13 }
14 
15 var toy=new Robot("Toy",2013,"Avary");
16 
17 console.log(toy.toString());
18 
19  
20 
21 function Robot2(name,year,owner)
22 
23 {
24 
25 this.name=name;
26 
27 this.year=year;
28 
29 this.owner=owner;
30 
31 }
32 
33 //重寫Object的toString方法
34 
35 Robot2.prototype.toString=function(){
36 
37 return this.name+" Robot2 beloneing to "+this.owner;
38 
39 }
40 
41 var toy2=new Robot2("Toy",2013,"Avary");
42 
43 console.log(toy2.toString());
44 
45 </script>

 

  • 拓展內置對象

給String等內置對象添加新方法時,務必確保新方法名稱不與對象既有名稱衝突,鏈接其他代碼時一定要清楚這些代碼包含的自定義拓展,有些內置對象如Array不能拓展

 1 <script>
 2 
 3 //爲String的原型添加方法cliche
 4 
 5 String.prototype.cliche=function(){
 6 
 7 var cliche=["lock and load","touch base","open the kimono"];
 8 
 9  
10 
11 for(var i=0;i<cliche.length;i++){
12 
13 var index=this.indexOf(cliche[i]);
14 
15 if(index>=0){
16 
17 return true;
18 
19 }
20 
21 }
22 
23 return false;
24 
25 }
26 
27  
28 
29 var sentences=["I'll send my car around to pick you up",
30 
31 "Let's touch base in the moring and see where we are",
32 
33 "We don't want to open the kimono,we just want to inform them."];
34 
35 for(var i=0;i<sentences.length;i++){
36 
37 var parse=sentences[i];
38 
39 if(parse.cliche){
40 
41 console.log("CliCHE ALERT: "+parse);
42 
43 }
44 
45 }
46 
47 </script>

 

原文出處:https://www.cnblogs.com/weimingai/p/10349205.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章