主要问题是:为何要做A.prototype.constructor=A这样的修正?
参考前两个链接就可以大致了解。
我们知道,每个函数都有默认的prototype,这个prototype.constructor默认指向的就是这个函数本身。在未给Woman指定Person作为原型之前,Woman.prototype.constructor或者woman.proto.constructor指向的就是Woman函数。但是当这样做之后:
Woman.prototype=new Person();
配合上面代码,主要要理解下面这段话:
我们知道,constructor始终指向的是创建本身的构造函数,因此Woman.prototype.constructor自然就指向了创建Woman.prototype这个Person对象的函数,也就是Person函数。
这样一来,woman对象的constructor指向就不对了,因此在网上大多关于原型继承的帖子里都会建议我们做这样的修改:
Woman.prototype.constructor=Woman;
var woman=new Woman();//in 'Woman'
woman.constructor;//function Woman(){console.log("in 'woman'");}
这样修正以后,constructor的指向就正确了。
或者我们可以下面这样的思路进行理解:
class Animal {
constructor(name){
this.name = name
}
eat(){
alert(this.name + ' eat')
}
}
class Dog extends Animal{
constructor(name){
super(name)
}
say(){
alert(this.name + ' say')
}
}
const dog = new Dog('哈士奇')
dog.say()
我们还要注意一个问题,关于constructor指向的修正的问题,先看下面代码。
Dog.prototype = new Animal()
但是这样子写的话,dog 的构造函数就成 animal 的构造函数了,如下:
Dog.prototype.constructor == Animal.prototype.constructor == Animal
所以,指向了Animal构造函数,所以一般加上下面代码进行修正:
Dog.prototype.constructor = Dog
参考文章:
https://www.cnblogs.com/dolphinX/p/3286177.html
https://www.cnblogs.com/SheilaSun/p/4397918.html
https://www.jianshu.com/p/9704185c5105
https://notes.iissnan.com/2012/ensure-construct-property-when-rewrite-prototype-in-javascript/