js 继承原理

107 阅读2分钟

问题思考

  1. 继承是什么意思?
  2. 什么继承什么?
  3. 什么才是完美的继承?

问题解答

1.继承是什么意思?

比如说“动物”与“人类”,人类继承了动物的特性,在js中

function animal(){   
}

function human(){
}

这两个function声明并不知道彼此有什么联系,但我们实际使用的时候希望‘animal’的一些特性能被人拷贝过来

function animal(){
}
animal.prototype.behaviors //动物有的一些行为

function human(){
}
// 现在我们需要实现human.prototype.behaviors能包含动物的基本行为,
// 这只是一部分功能的继承,我们还需要继承动物的character
function animal(){
    this.character = 'animal'
}

上面继承的意思就是‘human’这个函数想拥有‘animal’的特性,如果人有了动物特性和行为,就叫人继承于动物

2.什么继承什么

function都有一个prototype属性animal.prototype,这个属性又有个属性叫constructor,这个constructor继承过来的时候需要指向人类的构造函数

function animal(){
 this.character = 'animal'
}
animal.prototype.behaviors //动物有的一些行为
animal.prototype.constructor === animal // true

// 我们谈论的完美继承是下面三个实现

// 1.继承动物的prototype

// 2.继承character(构造函数内的属性)

// 3.animal.prototype.constructor = human

3.实现上述完美的继承

function animal(){
 this.character = 'animal'
}

function human(){
    animal.call(this) 
    // 这一步是执行一遍animal的构造函数,
    // 只是animal构造函数内的this却是human实例,意思就是给human实例加上.character = 'animal'
    this.diffrentCharacter = 'human'
}

1. human.prototype = Object.create(animal.prototype)
// 把animal的prototype拷贝过来,不让其他human实例修改human.prototype的时候影响到其他的human实例

2. human.prototype.constructor = human
// 这一步是js规定的,人类构造函数的原型上的构造函数只能指向人类构造函数

实验

function animal(){
 this.character = 'animal'
}
animal.prototype.hasBones = true

function human(){
    animal.call(this) 
    this.diffrentCharacter = 'human'
}
human.prototype = Object.create(animal.prototype)
human.prototype.constructor = human

const human1 = new human()
console.log(human1, human1.hasBones)
VM1461:14 human {character: 'animal', diffrentCharacter: 'human'} true