原型链的概念
在oo语言中都会谈到继承这一要素,js原型链的出现解决了继承的问题。
简单回顾一下构造函数、原型和实例的关系:
每个构造函数都有一个原型对象
原型对象都包含一个指向构造函数的指针
实例都包含一个指向原型对象的内部指针
function Person(){
this.name='xihongshidalumao'
}
let person = new Person()
就比如上面这个例子,person实例和Person对象的prototype指向Person prototype, 而Person prototype中的构造函数又重新指会Person对象。
那么我们现在将代码进行如下修改:
function Person(){
this.name='xihongshidalumao'
}
let person = new Person()
console.log(person)
function Leader(){
this.position='boss'
}
// 继承
Leader.prototype = new Person()
let leader = new Leader()
console.log(leader)
新创建一个Leader对象,然后将对象的prototype指向new Person,这样就修改了Leader prototype中的consructor指向了Person protytype。
这样就可以访问我父类中的属性,如果我们以此类推,就可以让多个类通过修改prototype来进行继承修改,也就形成类原型链。
如果我们现在想执行leader.name,那么会经历这三个步骤:
1.搜索实例
2.搜索Leader prototype
3.搜索Person prototype
object才是祖宗
在原型链中,不管如何继承,都是继承了object。就比如在调用toString()函数的时候,其实就是搜索的object中的toString()
除此之外,我们可以用instanceof和isPrototypeof这两种方法来确定这个关系。
console.log(leader instanceof Object) // ture
console.log(Object.prototype.isPrototypeOf(leader)) // ture
原型链的问题
原型链固然强大,但是所有的实例都会共享原型中的属性,所以在定义数据的时候最好在构造函数中定义。
function Person(){
this.color = ["red","yellow"]
}
function Dog(){}
let person = new Person()
Dog.prototype = new Person()
let dog = new Dog()
let dog2 = new Dog()
dog.color.push("green")
console.log(dog.color) //["red", "yellow", "green"]
console.log(dog2.color) //["red", "yellow", "green"]
第二个问题就是,在原型链中,子类无法通过父类的构造函数传递参数。
function Person(color){
this.color = color
}
function Dog(){}
let person = new Person(["red", "yellow", "green"])
Dog.prototype = new Person(["red", "yellow"])
let dog = new Dog()
let dog2 = new Dog()
console.log(person.color) //["red", "yellow", "green"]
console.log(dog.color) //["red", "yellow"]
console.log(dog2.color) //["red", "yellow"]
通过构造函数传参,person 和 Dog分别new 了两个Person,导致person.color和dog.color出现不同的结果,但是dog和dog2之间的结果是相同的。所以为了解决这一个问题,提出了借用构造函数。
借用构造函数
其实原理很简单,就是在子类中调用一次父类的构造函数。一般是通过apply和call绑定this这一方式进行。
function Person(color){
this.color = color
}
function Dog(color){
Person.call(this,color)
}
Dog.prototype = new Person()
let dog = new Dog(["red", "yellow", "green"])
let dog2 = new Dog(["red", "yellow"])
console.log(dog.color) // ["red", "yellow", "green"]
console.log(dog2.color) // ["red", "yellow"]
当然借用构造函数也有他的问题,由于方法都在构造函数中定义,所以导致无法对方法进行函数复用。在超类型的原型中定义的方法,对子类型而言也是不可见的,结果所有类型都只能使用构造函数模式。
组合继承
只要思想不滑坡,办法总比困难多,由于上面出现的问题,程序猿们又发明出了组合继承,其实就是是将原型链和借用构造函数的技术组合到一块。
不废话,上🌰。
function Person(name){
this.name = name
this.has = ["leg","head","body","arm"]
this.sayName = function(){
console.log(this.name)
}
}
function Boss(name){
Person.call(this,name)
}
Boss.prototype = new Person()
Boss.prototype.constructor = Boss
Boss.prototype.sayHas = function(){
console.log(this.has)
}
let boss1 = new Boss("boss")
let boss2 = new Boss("little boss")
console.log(boss1.name)
console.log(boss2.name)
boss1.has.push("old")
boss2.has.push("little")
console.log(boss1.has)
console.log(boss2.has)
boss1.sayName()
boss2.sayName()
boss1.sayHas()
boss2.sayHas()