JS继承模式

  • 使用原型链继承

    • 定义父类型构造函数
    • 给父类型的原型添加方法
    • 定义子类型的构造函数
    • 创建父类型的对象赋值给子类型的原型
    • 将子类型原型的构造属性设置为子类型
    • 给子类型原型添加方法
    • 创建子类型的对象:可以调用父类型的方法
  • 关键:子类型的原型为父类型的一个实例对象

function Person(name,age){
    this.name=name;
    this.age=age;
}
Person.prototype.setName=function(name){
    this.name=name;
}
Person.prototype.printInfo=function(){
    console.log(this.name,this.age)
}
function Student(name,age,major){
    this.name=name;
    this.age=age;
    this.major=major;
}
var p=new Person();

Student.prototype=p;
Student.prototype.constructor=Student
Student.prototype.study=function(){
  console.log("study is called")
}

var s1=new Student("rose",30,"it")
s1.study();
s1.setName("jakc")
s1.printInfo()

借用构造函数继承

  • 使用super函数
function Person(name,age){
    this.name=name;
    this.age=age;
}
function Student(name,age,major){
    Person(name,age)-------这里的函数调用进去,this是window
    this.major=major;
}

var s=new Student("jack",20,"it")
console.log(s)
OUTPUT:所以Person的this.name=name设置在window上了
  • 解决上面this不正确的问题
function Person(name,age){
    this.name=name;
    this.age=age;
}
function Student(name,age,major){
    Person.call(this.name,age)
    this.major=major;
}

原型链与构造函数组合继承

  • 利用原型链实现对父类型对象的方法继承
  • 利用super()借用父类型构建函数初始化相同属性
posted @ 2021-02-23 16:56  abcdefgab  阅读(64)  评论(0)    收藏  举报