js知识汇总

84 阅读1分钟

继承

原型链继承

function people(){
    this.child = ['张三','李四']
}
people.prototype.getName = function(){
    return this.name
}
function person1(){}
person1.prototype = new people()
let test1 = new person1()
test1.child.push('汪峰')
let test2 = new person1()
console.log(test2.child) // 张三 李四 汪峰

原型链继承存在的问题:

  • 问题1:原型中包含的引用类型属性将被所有实例共享;
  • 问题2:子类在实例化的时候不能给父类构造函数传参;

借用构造函数实现继承

function people(name){
    this.name = name
    this.getName = function(){
        return this.name
    }
}
function person(name){
    people.call(this,name)
}
person.prototype = new people()
let people1 = new people('张三')
let person1 = new person('王五')
console.log(person.prototype.constructor)
console.log(people1.name)

存在的问题:

  • 1.方法只能写在构造函数中
  • 2.子类每创建一次就会创建一编方法

组合继承

function people(name){
    this.name = name
}
people.prototype.getName = function(){
    return this.name
}
function person(name){
    people.call(this,name)
}
person.prototype = new people()
person.prototype.constructor = person
let person1 = new person('王富贵')

存在的问题: 1.会调用两遍父类构造函数 2.子类修改constructor父类也会变

寄生继承

将
person.prototype = new people()
person.prototype.constructor = person
改为
function P(){
}
P.prototype = people.prototype
let p = new p()
p.constructor = person
可以简写为
person.prototype = Object.create(people.prototype)
person.prototype.constructor = person

class继承

class people {
    constructor(name){
        this.name = name
    }
    getName(){
        return this.name
    }
}
class person extends people{
    constructor(name){
        super(name)
    }
}