class类 和其对应的super方法。
在es6出class之前类是怎么写的:
栗子,function father(str, num, obj){
/.../
}
上面的是声明了一个父类。子类如果要使用父类中的属性或者方法,那它必须在父类的原型链上
这么写:
father.prototype.aa = function() {}
上面的意思是在father的原型链上声明了一个叫aa的函数,这样father的字类都可以通过原型链访问到aa这个函数。
然后声明子类
function child (str, num) {
// 这里的call是显式绑定this指向,引入父类的基础方法。
father.call(this, str, num);
/…/
}
然后子类继承父类的原型链
child.prototype = Object.create(father.prototype);
如果子类要重写父类的方法可以这样
childe.prototype.aa = function(obj) {
// 重写后的参数配置同理
father.protptype.aa.call(this, obj)
/…/
}
上面的整个流程就是传统的类及及其继承的写法。但是问题也很明显,大家都觉得call这种从子类中引入父类基础方法的行为特别丑陋。所以就有了es6的语法糖,class。
class的使用如下
声明一个父类
class father {
constructor(str, num, obj) {
/.../
},
aa(obj) {
/.../
}
}
然后子类引入父类。
class child extends father {
constructor(str, num) {
super(str, num);
},
aa(obj) {
super.aa(obj)
}
}
super 的函数也是通过原型链去找父类的属性值。
class也是通过prototype机制实现
但是相对于call的这种写法就简介很多