JS篇 - 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
    原文作者:呵sever
    原文地址: https://segmentfault.com/a/1190000019198758
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞