javascript继承的几种实现方法

川长思鸟来 2023-03-04 06:49 115阅读 0赞

1.构造函数继承 (无法继承父类原型链上的属性)

  1. function Animal() {
  2. this.type = '猫科动物';
  3. }
  4. function cat(name, age) {
  5. this.name = name;
  6. this.age = age;
  7. Animal.call(this); //方法一:使用call方法继承
  8. }
  9. // cat.prototype = new Animal(); //方法2:使用prototype属性
  10. cat.prototype.constructor = cat;
  11. var cat = new cat('小猫', 2);
  12. console.log(cat.type + cat.name + cat.age)

2.原型继承 (所有属性被共享,而且不能传递参数)

  1. function person() {
  2. this.sex = "男性"
  3. }
  4. function son(name, age) {
  5. this.name = name;
  6. this.age = age;
  7. }
  8. son.prototype = new person(); //原型继承
  9. son.prototype.constructor = son;
  10. var son = new son('小明', 23)
  11. console.log(son.sex + son.name);

3.构造函数和原型的混合继承

  1. //构造函数
  2. function person1() {
  3. this.name = "哈克"
  4. }
  5. function child() {
  6. this.age = 23;
  7. }
  8. //原型继承,child函数继承了person函数的属性和方法
  9. child.prototype = new person1();
  10. //任何一个prototype对象都有一个constructor属性,指向它的构造函数,如果没有child.prototype = new
  11. //person() 这句话, child.prototype.constructor是指向child的, 加入这行之后, child.prototype.constructor是指向person的
  12. child.prototype.constructor = child;
  13. //实例化child()函数
  14. var demo = new child();
  15. console.log(demo.name); //得到被继承的属性
  16. //alert(demo.age)

4. es6继承方法

  1. //ES6引入了class类的概念,创建的每一个class类,都会有一个constructor()方法,该方法是一种用于创建和初始化class创建的对象的特殊方法--构造函数方法。
  2. //constructor()方法里的 this 指向的是被创建的实例对象
  3. class per { //class
  4. constructor(name) {
  5. this.name = name;
  6. }
  7. sayName() {
  8. console.log(this.name);
  9. }
  10. }
  11. class Son extends per {
  12. constructor(name, age) {
  13. super(name) //类似java的继承方法
  14. this.age = age;
  15. }
  16. }
  17. var son = new Son("张三", 25);
  18. console.log(son);
  19. son.sayName(); //从per继承过来的方法

5.寄生组合继承 (解决构造函数继承无法继承原型的属性)

  1. function animal(name) {
  2. this.name = name;
  3. this.sleep = function () {
  4. console.log(this.name + "在睡觉");
  5. }
  6. }
  7. //增加原型属性
  8. animal.prototype.eat = function (food) {
  9. console.log(this.name + '正在吃' + food);
  10. }
  11. function fish(name) {
  12. animal.call(this, name); //构造继承父类
  13. }
  14. //创建一个没有实例的对象函数
  15. var Super = function () { };
  16. //为了使子类可以继承父类的原型属性; eat()方法
  17. Super.prototype = animal.prototype;
  18. fish.prototype = new Super(); //原型继承
  19. fish.prototype.constructor = fish;
  20. var fish = new fish("金鱼");
  21. console.log(fish.name);
  22. fish.sleep(); //从父类继承过来的
  23. fish.eat('食物')

几种继承方法的代码运行结果截图

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,115人围观)

还没有评论,来说两句吧...

相关阅读