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 }