继承

 

继承

⽅法1:原型链继承

//⽗类型
function Body() {
    this.volumes = {
        _bloodVolume: 1000,
        _attackVolume: 500,
        _defenseVolume: 200
    };
}
Body.prototype.attacked = function (body) {
    this.volumes._bloodVolume -= body.getAttackVolume() - this.volumes._defenseVolume;
};
//⼦类型
function Monster() {};
Monster.prototype = new Body();
Monster.prototype.attacked = function () {
    this.volumes._bloodVolume -= 1;
};
var monster = new Monster();
var monster2 = new Monster();
monster.attacked();
console.log(monster2.volumes._bloodVolume);

所有新实例都会共享父类实例的属性。(原型上的属性是共享的,一个实例修改了原型属性,另一个实例的原型属性也会被修改)

monster改变_bloodVolume后,monster2的_bloodVolume也被改变了。

⽅法2:借⽤构造函数继承

// ⽗类
function Body() {
    this._bloodVolume = 1000;
    this._attackVolume = 500;
    this._defenseVolume = 200;
}
Body.prototype.attacked = function (body) {
    this._bloodVolume -= body.getAttackVolume() - this._defenseVolume;
};
// ⼦类
function Monster() {
    Body.call(this);
};
var monster = new Monster();

注意:这种⽅式,Monster⽆法继承⽗类prototype上的⽅法和属性

⽅法3: 原型链+借⽤构造函数的组合继承

// ⽗类
function Body() {
    this._bloodVolume = 1000;
    this._attackVolume = 500;
    this._defenseVolume = 200;
}
Body.prototype.attacked = function (body) {
    this._bloodVolume -= body.getAttackVolume() - this._defenseVolume;
};
// ⼦类
function Monster() {
    Body.call(this);
}
Monster.prototype = new Body();
var monster = new Monster();

调用了两次父类构造函数(耗内存),子类的构造函数会代替原型上的那个父类构造函数。

⽅法4:寄⽣组合继承

// ⽗类
function Body() {
    this._bloodVolume = 1000;
    this._attackVolume = 500;
    this._defenseVolume = 200;
}
Body.prototype.attacked = function (body) {
    this._bloodVolume -= body.getAttackVolume() - this._defenseVolume;
};
// ⼦类
function Monster() {
    this.name = 'asd';
    Body.call(this);
}
// Object.create实质上是新建一个空的构造函数,然后继承Body.prototype
// 然后让Monster.prototype指向新建的构造函数,这样改变子类不会影响父类
Monster.prototype = Object.create(Body.prototype);
// 让Monster.prototype重新指向Monster
Monster.prototype.constructor = Monster
var monster = new Monster();

如果Monster.prototype被修改,比如 Monster.prototype = {} 那它的constructor会指向Object,

Monster.prototype.att = function(){} 这是在原型对象上添加新的方法,不会改变constructor

⽅法5:es6的class

// ⽗类
class Body {
    constructor() {
        this._bloodVolume = 1000;
        this._attackVolume = 500;
        this._defenseVolume = 200;
    }
    attacked(body) {
        this._bloodVolume -= body.getAttackVolume() - this._defenseVolume;
    }
}
// ⼦类
class Monster extends Body {
    constructor() {
        super();
    }
    attacked() {
        this._bloodVolume -= 1;
    }
}
var monster = new Monster();

 

 

 

 

 

你可能感兴趣的:(JavaScript)