Thanks to visit codestin.com
Credit goes to github.com

Skip to content

JS继承对比 #20

@Clearives

Description

@Clearives

JS继承

JS的继承方式有很多种,最理想的继承方式是寄生组合式继承。

组合继承

function Person(name) {
    this.name = name;
}
Person.prototype.sayHi = function() {
    console.log(this.name + '-' + '-hi');
}

function SubPerson(name, age) {
    Person.call(this, name);
    this.age = age;
}

SubPerson.prototype = new Person();
SubPerson.prototype.constrcutor = SubPerson;

var sp = new SubPerson('clearives', 18);
console.log(sp);
sp.sayHi();

组合继承(构造函数和原型的组合)会调用两次父类构造函数的代码

寄生组合式继承

function inheritPrototype(SubPerson, Person){ 
  var protoType = Object.create(Person.prototype);
  protoType.constructor = SubPerson;
  SubPerson.prototype = protoType;
}
function Person(name) {
    this.name = name;
}
Person.prototype.sayHi = function() {
    console.log(this.name + '-' + '-hi')
}

function SubPerson(name, age) {
    Person.call(this, name);
    this.age = age;
}

inheritPrototype(SubPerson, Person);

var sp = new SubPerson('clearives', 18);
console.log(sp);
sp.sayHi();

这样避免了调用两次父类的构造函数,为其创建多余的属性。

其它

function object(o) {
    function F(){}
    F.prototype = o;
    return new F();
}
// 这个函数其实就是Object.create的简单实现

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions