面向对象编程/原型及原型链

117 阅读1分钟

面向对象编程/原型及原型链

new的原理?/ new是什么?/ new的时候做了什么?

  1. 结构上: 创建了一个空对象,作为返回的对象实例
  2. **属性上:**将生成空对象的原型对象指向了构造函数的prototype属性
  3. **关系上:**将当前实例对象赋给了内部的this
  4. **生命周期上:**执行了构造函数的初始化代码

如果构造函数中显式地返回一个对象(可能是新创建的对象,也可能是其他对象),那么new操作符返回的就是这个显式返回的对象,而不是刚刚创建的新对象。

constructor是什么?

  1. 每个对象在创建时,会自动拥有一个构造函数属性constructor
  2. constructor源自原型对象,指向了构造函数的引用

寄生组合继承

function Game(arg) {
  this.name = "lol";
  this.skin = "default";
}
Game.prototype.getName = function () {
  return this.name;
};

function LoL(arg) {
  Game.call(this, arg);
}

LoL.prototype = Object.create(Game.prototype);
LoL.prototype.constructor = LoL;
const game = new LoL();

多重继承

function Game(arg) {
  this.name = "lol";
  this.skin = "default";
}
Game.prototype.getName = function () {
  return this.name;
};

function RpgGame(arg) {
  this.type = "rpg";
}

function LoL(arg) {
  Game.call(this, arg);
  RpgGame.call(this, arg);
}

LoL.prototype = Object.assign({}, Game.prototype, RpgGame.prototype);
LoL.prototype.constructor = LoL;
const game = new LoL();