1. 原型链继承
从父级上继承,但是有个问题,如果有多个子类同时继承一个父类,如果改变其中一个子类,其余子类也会跟着改变,这种情况就和数组对象的浅拷贝一样。
function parents(){ this.name = ['fuqin'] } parents.prototype.getName = function() { console.log(this.name) } function child(){} child.prototype = new parents() let child1 = new child() child1.getName() // ['fuqin'] let child2 = new child() child1.name.push('haha') let child3 = new child() child1.getName() // => ['fuqin', 'haha'] child2.getName() // => ['fuqin', 'haha'] child3.getName() // => ['fuqin', 'haha']
2. 构造函数继承
改进了原型链继承的缺点,不会因为某个实例的更改而导致所有继承实例的变化,但是也有它的缺点就是每次创建实例都会创建一遍方法。
function parents(){ this.name = ['brother'] } function child(){ parents.call(this) } let child1 = new child() let child2 = new child() child1.name.push('haah') let child3 = new child() console.log(child1.name) // => ['brother', 'haah'] console.log(child2.name) // => ['brother'] console.log(child3.name) // => ['brother']
// 在构造函数继承中还可以通过call()传递参数
function parents(name){ this.name = name } function child(name){ parents.call(this,name) } let child1 = new child('hh,我是1') let child2 = new child('hh,我是2') child1.name // => 'hh,我是1' child2.name // => 'hh,我是2'