js 继承

2017-07-23  本文已影响9人  ci0n

4种继承方式

  1. 原型式继承
    1. 给原型对象添加属性
    2. 原型替换
    3. 子类的原型对象替换为父类的原型对象
  2. 原型链继承
  3. 借用构造函数继承(经典式继承)
  4. 组合继承

1 原型式继承

给原型对象添加属性

function Person (name){
    this.name = name;
}
Person.prototype.eat = function(){
    console.log('eat');
}
var p1 = new Person('p1');
p1.eat();   // eat

原型替换

function Person(name) {
    this.name = name;
}
Person.prototype = {
    constructor: Person,    // 别忘记这个了!
    eat: function(){
        console.log('eat');
    }
};
var p1 = new Person('p1');
p1.eat();   // eat

子类的原型对象替换为父类的原型对象

function Animal () {
    this.name = 'Animal';
}
Animal.prototype.info = 'des Animal';

function Person () {
    this. name = 'Person';
}
Person.prototype = Animal.prototype;
Person.prototype.constructor = Person;

2 原型链继承

子类的原型方法替换为父类的实例

function Animal(){
    this.name = 'Animal';
}
Animal.prototype.info = 'des Animal';

function Person(age){
    this.age = age;
}
Person.prototype = new Animal();
Person.prototype.constructor = Person;

var p1 = new Person(18);
console.log(p1.name);   // Animal
console.log(p1.info);   // des Animal
console.log(p1.age);    // 18

原型链继承缺陷示例代码:

function Animal(name){
    this.name = name;
    this.friends = ['zs', 'ls'];
}
Animal.prototype.info = 'des Animal';

function Person(age){
    this.age = age;
}
Person.prototype = new Animal();    // 无法传递参数
Person.prototype.constructor = Person;

var p1 = new Person(18);
p1.friends.push('xm');
p1.__proto__.name = 'ww';

var p2 = new Person(22);
console.log(p2.friends);    // zs ls xm
console.log(p2.name);   // ww

3 借用构造函数继承(经典式继承)

借用apply和call方法实现继承

// 父类
function Animal (name) {
    this.name = name;
    this.logName = function () {
        console.log(this.name);
    }
}

// 子类
function Person (name){
    Animal.call(this, name);
}

var p1 = new Person('p1');
console.log(p1);    // Person {name: "p1", logName: function}

4 组合式继承

借用构造函数继承 + 原型式继承

// 父类
function Animal (name) {
    this.name = name;
    this.logName = function () {
        console.log(this.name);
    }
}
Animal.prototype = {
    constructor: Animal,
    logDes: function () {
        console.log('des');
    }
};

// 子类
function Person (name){
    Animal.call(this, name);
}

Person.prototype = Animal.prototype;
Person.prototype.constructor = Person;

var p1 = new Person('p1');
console.log(p1);
上一篇 下一篇

猜你喜欢

热点阅读