面向对象编程/原型及原型链
new的原理?/ new是什么?/ new的时候做了什么?
- 结构上: 创建了一个空对象,作为返回的对象实例
- **属性上:**将生成空对象的原型对象指向了构造函数的prototype属性
- **关系上:**将当前实例对象赋给了内部的this
- **生命周期上:**执行了构造函数的初始化代码
如果构造函数中显式地返回一个对象(可能是新创建的对象,也可能是其他对象),那么new
操作符返回的就是这个显式返回的对象,而不是刚刚创建的新对象。
constructor是什么?
- 每个对象在创建时,会自动拥有一个构造函数属性constructor
- 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();