Loading

ES5和ES6的继承

对象的继承

var animal = {
  name:'name'
}

var dog = {}

// 子对象的原型链指向父对象即可
dog.__proto__ = animal
console.log(dog.name)

构造函数的继承

ES5继承

function Animal(name) {
  this.name = name;
}

Animal.prototype.sayName = function() {
  console.log('My name is ' + this.name);
};

function Dog(name) {
  // 把子类的 this 传入父类并执行父类函数,此时子类的 this 已有 name 属性
  Animal.call(this, name);
}
// Animal.prototype 是一个对象并且有 sayName 属性
Dog.prototype = Object.create(Animal.prototype);
// 正常来说函数的 prototype.constructor 属性指向函数本身,
// 则 Dog.prototype.constructor === Dog is true
// 上一行代码使 Dog.prototype.constructor === Animal is true,
// 所以要把 Dog.prototype.constructor 再次指向 Dog 函数本身
Dog.prototype.constructor = Dog;
// 在使用 new 关键字时会 调用 Dog.prototype.constructor
var dog = new Dog('Tom');
dog.sayName(); // My name is Tom

ES5继承引入了 class 关键字

class Animal {
  constructor(name) {
    this.name = name;
  }

  sayName() {
    console.log(`My name is ${this.name}`);
  }
}

class Dog extends Animal {
  constructor(name) {
    super(name);
  }
}

let dog = new Dog('Tom');
dog.sayName(); // My name is Tom

在子类 Dog 中 super 函数不能省略,否则会报错,实际是调用父类的 constructor 函数,并把 Dog 的 this 传入父类此时的父类 this.name = name 的 this 指向的是子类 Dog
ES6 和 ES5 本质是一样

new 关键字实质

在 ES5 的例子中

var dog = new Dog('Tom');
// 可替换为
var dog = {}  
dog.__proto__ = Dog.prototype
// 在此会调用 Dog.prototype.constructor
// 所以在 ES5 的例子中,必须 Dog.prototype.constructor = Dog; 重新指向 Dog 函数
Dog.call(dog, 'Tom')
posted @ 2023-11-24 16:20  _尼欧`  阅读(4)  评论(0编辑  收藏  举报