拷贝继承
1 function Foo(){ //父类 2 this.name = 'hello'; 3 } 4 Foo.prototype.showName = function(){ 5 console.log(this.name); 6 }; 7 function Bar(){ //子类 8 Foo.call(this); 9 this.age = 20; 10 this.name = 'hi' 11 } 12 extend(Bar,Foo); 13 Bar.prototype.showAge = function(){ 14 console.log(this.age); 15 }; 16 function extend(subs,sups){ 17 for(var attr in sups.prototype){ 18 subs.prototype[attr] = sups.prototype[attr]; 19 } 20 } 21 var obj1 = new Foo(); 22 var obj2 = new Bar(); 23 console.log(obj1); 24 console.log(obj2); 25 obj2.showName()
类式继承
1 function Foo(){ 2 this.name = 'hello'; 3 } 4 Foo.prototype.showName = function(){ 5 console.log(this.name); 6 }; 7 function Bar(){ 8 Foo.call(this); 9 this.age = 20; 10 } 11 extend(Bar,Foo); 12 Bar.prototype.showAge = function(){ 13 console.log(this.age); 14 }; 15 function extend(subs,sups){ 16 var F = function(){}; 17 F.prototype = sups.prototype; 18 subs.prototype = new F(); 19 // constructor 找对应的构造函数; 20 subs.prototype.constructor = subs; 21 } 22 var obj1 = new Foo(); 23 var obj2 = new Bar(); 24 console.log(obj1); 25 console.log(obj2);
非构造函数拷贝继承
1 var foo = { 2 name : 'hello' 3 }; 4 foo.showName = function(){ 5 console.log(this.name) 6 } 7 var bar = extend(foo); 8 function extend(sups){ 9 var result = {}; 10 for(var attr in sups){ 11 result[attr] = sups[attr]; 12 } 13 return result; 14 } 15 console.log(bar); 16 bar.name = 'hi'; 17 console.log(bar); 18 console.log(foo); 19 bar.showName();
原型链形式
1 var foo = { 2 name : 'hello', 3 showName: function(){ 4 console.log(this.name) 5 } 6 }; 7 var bar = extend(foo); 8 function extend(sups){ 9 function F() {} 10 F.prototype = sups; 11 return new F(); 12 } 13 console.log(bar); 14 bar.name = 'hi'; 15 console.log(bar); 16 console.log(foo); 17 bar.showName()