谈谈js的继承

发布时间:2019-08-11 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了谈谈js的继承脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

定义

汉语解释:泛指把前人的作风、文化、知识等接受过来
计算机语解释:继承可以使得子类具有父类的属性和方法或者重新定义、追加属性和方法等

先来个父类祭天

  function Animal(name) {
    this.name = name || 'animal';
    this.sPEak = function () {
      console.LOG('speak');
    }
  }
  Animal.PRototype.move = function () {
    console.log('move');
  }

原型链继承

  function Cat() {
    this.getName = function () {
      console.log(this.name);
    };
  }

  Cat.prototype = new Animal('cat1');
  VAR cat = new Cat();
  cat.name = 'cat2';
  console.log(cat);//该实例对象有一个name为cat2,原型上有一个name是cat1
  cat.getName();//cat2(先找当前属性,再找原型)
  console.log(cat instanceof Cat);//true
  console.log(cat instanceof Animal);//true
父子之间存在关系,但子类并不会创建新的属性,set子类属性并不会覆盖原型上的属性,get属性只不过是根据先读取当前属性再读取原型的优先级

构造函数继承

  function Dog(name) {
    Animal.call(this);
    this.name = name || 'doggy';
  }

  var dog = new Dog();
  console.log(dog);//只有子类属性
  console.log(dog instanceof Dog); // true
  console.log(dog instanceof Animal); // false
实际上只是利用父类构造函数来添加子类属性,父子之间没有什么关系

ES6继承(完美继承)

  class Animal2 {
    constructor(name) {
      this.name = name || 'animal2';
      this.speak = function () {
        console.log('speak');
      }
    }
  }

  Animal2.prototype.move = function () {
    console.log('move');
  }
  var animal2 = new Animal2('god2');
  console.log(animal2);

  class Bird extends Animal2 {
    getName() {
      console.log(this.name);
    }
  }

  var bird = new Bird('bird');
  console.log(bird);//既有父类的属性,原型链也指向父类
  bird.getName();
  console.log(bird instanceof Bird); // true
  console.log(bird instanceof Animal2); // true

脚本宝典总结

以上是脚本宝典为你收集整理的谈谈js的继承全部内容,希望文章能够帮你解决谈谈js的继承所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。