class
首先先写一个简单的class看看
class a{
constructor(name){
this.name = name
}
sayname(){
console.log(this.name)
}
}
class b extends a{
constructor(name,age){
super(name)
this.age = age
}
sayage(){
console.log(this.age)
}
}
let B = new b();
console.dir(B)
如果是以前我是这么写的
//father构造函数
function father(name,work){
this.name = name
this.work = work
this.tag = 'father'
}
//添加静态方法
father.SB = function(){console.log('SB')}
//在原型上添加公共方法
father.prototype.dowork = function(){
console.log(`开始${this.work}挣钱吧`);
}
//son构造函数
function son(name,work){
father.call(this,name,work)
this.tag = 'son'
}
//将son的隐士原型指向father构造函数
son.__proto__ = father
//将son的显示原型对象中的隐士原型指向father的显示原型对象上
son.prototype.__proto__ = father.prototype;
//为son添加公共方法
son.prototype.sonfun = function(){
console.log(this.tag)
}
//观察对象
console.dir(father)
console.dir(son)
console.dir(son.prototype.__proto__.constructor.name)
然后看一下b类的实例对象B的内部结构。经梳理得如图:
extends 从图中可以看出来,class实现继承的方式是把子类的__proto__指向父类,和将子类的prototype中的__proto__指向父类的prototype。
- super 从功能上可以调用父类的构造方法和父类的方法,具体怎么实现的还不太清楚。
好奇
很好奇__proto__:后面的值怎么来的
猜测是当前__proto__对象.__proto__.constructor.name。除了顶层的class对象的显示原型对象的__proto__对象.__proto__==null ,所以直接调用显示原型对象的__proto__对象.constructor.name。