javascript类式继承最优版
直接看实例代码:
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>javascript类式继承</title> 6 </head> 7 <body> 8 <script> 9 var inherit = (function () { 10 var F = function () {}; 11 return function (C, P) { 12 F.prototype = P.prototype; 13 C.prototype = new F(); 14 C.prototype.constructor = C; 15 C.uber = P.prototype; 16 }; 17 } ()); 18 19 function Person(name) { 20 this.name = name || "Adam"; 21 } 22 Person.prototype.say = function () { 23 return this.name; 24 }; 25 26 function Child(name, age, sex) { 27 Person.apply(this, arguments); 28 this.age = age; 29 this.sex = sex; 30 } 31 32 inherit(Child, Person); 33 34 Child.prototype.getAge = function () { 35 return this.age; 36 }; 37 Child.prototype.getSex = function () { 38 return this.sex; 39 }; 40 41 var c = new Child('fengyuqing', 23, 'male'); 42 console.log(c.say()); 43 console.log(c.getAge()); 44 console.log(c.getSex()); 45 </script> 46 </body> 47 </html>