关于javascript:js中的几种继承方法以及优缺点

先定义一个构造函数:

function Person(name,age){
    this.name = name;
    this.age = age;
    this.say = function(){
        console.log("hello world")
    }
}
Person.prototype.gender = male;

1.原型链继承:将子类的构造函数的原型变为父类的实例对象

Student.prototype = new Person();
Student.prototype.constructor = Student

长处:实现简略
毛病:无奈向父构造函数传参

2.通过构造函数继承

function Student(name,age){
    Person.call(this,name,age)
    this.name = name;
    this.age = age;
    this.say = function(){
        console.log("hello world")
    }
}

毛病:无法访问父构造函数的原型中的办法

3.将子构造函数的原型批改为父构造函数的原型

function Student(name,age){
    Person.call(this,name,age)
    this.name = name;
    this.age = age;
    this.say = function(){
        console.log("hello world")
    }
}
Student.prototype = Person.prototype
Student.prototype.constructor = Student

毛病:毁坏了原型链,给子类的原型增加属性父类原型也会增加

4.将子类的原型设置为父类的实例对象

  function Student(name,age){
    Person.call(this,name,age)
    this.name = name;
    this.age = age;
    this.say = function(){
        console.log("hello world")
        }
    }  
  Student.prototype = new Person();

毛病:调用了两次父类构造函数,耗费内存

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理