Javascript 面向對象 學習筆記


 1 //類定義(prototype 模式)
 2 function Cat(name,color) {
 3     this.name = name;
 4     this.color = color;
 5 }
 6 Cat.prototype.type = 'cat';
 7 Cat.prototype.food = 'fish';
 8 Cat.prototype.eat = function() {
 9     alert(this.name + ' is eating '+this.food);
10 };
11 
12 //使用
13 var cat1 = new Cat('Jack','white');
14 var cat2 = new Cat('Rose','black');
15 alert(cat1.name + ' is a ' + cat1.color + ' ' + cat1.type);//Jack is a white cat
16 cat2.eat();//Rose is eating fish
17 
18 //===========================================
19 
20 //繼承(利用空對象作為中介)
21 function extend(Child, Parent) {
22     var F = function(){};
23   F.prototype = Parent.prototype;
24     Child.prototype = new F();
25     Child.prototype.constructor = Child;
26 }
27 //使用
28 function Panda(name) {
29     this.name = name;
30     this.color = 'black&white';
31   this.food = 'bamboo';
32     this.size = 'fat';
33 }
34 extend(Panda, Cat);//Panda繼承Cat,假設熊貓是喵星人
35 
36 var panda1 = new Panda('Po');
37 alert(panda1.name + ' is a ' + panda1.color + ' ' + panda1.size + ' ' + panda1.type);//Po is a black&white fat cat
38 panda1.eat();//Po is eating bamboo
39 //=========================================
40 
41 //深拷貝函數
42 //p:parent c:child
43 function deepCopy (p ,c) {
44     var c = c || {};
45     for (var i in p) {
46         if(typeof p[i] === 'object') {
47             c[i] = (p[i].constructor === Array) ? [] : {};
48             deepCopy(p[i], c[i]);
49         } else {
50             c[i] = p[i];
51         }
52     }
53     return c;
54 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM