你的位置:首页 > 软件开发 > Java > JS原型继承与类的继承

JS原型继承与类的继承

发布时间:2016-04-07 12:00:11
我们先看JS类的继承 1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>JS类的继承& ...
  1.   我们先看JS类的继承

 

  1.  1 <!DOCTYPE html> 2 <html> 3  4 <head> 5   <meta charset="UTF-8"> 6     <title>JS类的继承</title> 7 </head> 8  9 <body>10   /* -- 类式继承 -- */11   <script type="text/javascript">12   //先声明一个超类13   var Animal = function(name) {14       this.name = name;15     }16     //给这个超类的原型对象上添加方法17   Animal.prototype.Eat = function() {18     console.log(this.name + " Eat");19   };20   //实例化这个超21   var a = new Animal("Animal");22 23   //再创建构造函数对象类24   var Cat = function(name, sex) {25       //这个类中要调用超类Animal的构造函数,并将参数name传给它26       Animal.call(this, name);27       this.sex = sex;28     }29     //这个子类的原型对象等于超类的实例30   Cat.prototype = new Animal();31   //因为子类的原型对象等于超类的实例,所以prototype.constructor这个方法也等于超类构造函数32 33   console.log(Cat.prototype.constructor);34   //这个是Animal超类的引用,所以要从新赋值为自己本身35   Cat.prototype.constructor = Cat;36   console.log(Cat.prototype.constructor);37   //子类本身添加了getSex 方法38   Cat.prototype.getSex = function() {39       return this.sex;40     }41     //实例化这个子类42   var _m = new Cat('cat', 'male');43   //自身的方法44   console.log(_m.getSex()); //male45   //继承超类的方法46   console.log(_m.Eat()); //cat47   </script>48 </body>49 50 </html>

    原标题:JS原型继承与类的继承

    关键词:JS

JS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。