工作中一直专注于写业务逻辑,猛然发现原生 JS 基础没怎么提升。Later better than never ,最近又去翻看高程3(红宝石书),果然知识就是推翻旧有体系搭建新的过程。
以前写过一篇文章浅显的讲了讲 JS 中 Class 的发展历程,以及简单的继承
(Javascript之class的前世今生,主要看看里面画的两张原型链继承图),
今天打算通过我新的知识体系,深入 ES6 的 Class
首先创建一个类 Reactangle
class Reactangle{
constructor(height,width){
this.height = height
this.width = width
this.getHeight = function(){
return this.height
}
}
getArea(){
return this.height * this.width
}
}
通过创建这个类的实例 ,查看该实例内容
发现这个实例有两个属性(height,width),一个方法(getHeight),还有一个原型上的实例方法(getArea)
我们用 ES5 的写法写出同样的函数,不就是 ES6 Class 的原生写法:
function Reactangle(height,width){
this.height = height
this.width = width
this.getHeight = function(){
return this.height
}
}
Reactangle.prototype.getArea = function(){
return this.height * this.width
}
通过 ES5 代码反推 ES6 ,
(1) Class 中的方法就是定义该函数原型对象上的方法
(2) Class 中,constructor 方法内就是在定义构造函数内的属性和方法
有了类的创建,肯定也要讲讲类的继承
创建一个类 triangle 继承自 Reactangle
class triangle extends Reactangle{
constructor(height,width,color){
super(height,width)
this.color = color
}
getArea(){
return super.getArea()/2
}
}
通过创建这个类的实例 child,查看该实例内容
这个实例 child 不仅继承了类 Reactangle 的两个属性(height,width),一个方法(getHeight),一个构造方法(getArea);还有了类 triangle 自己的属性(color)和改造了的原型方法(getArea)
可以发现,在 Class 中调用 super 关键字,在这里表示父类的构造函数
试着写出继承的原生写法(使用了高程3中的寄生组合式继承):
function triangle(height,width,color){
Reactangle.call(this,height,width)
this.color = color
}
function inherit(Sub,Super){
var property = Object.create(Super.prototype)
property.constructor = Sub
Sub.prototype = property
}
inherit(triangle,Reactangle)
triangle.prototype.getArea = function(){
return Reactangle.prototype.getArea.call(this)/2
}
也可以使用ES6 的新方法 setPrototypeOf 实现继承
function Reactangle(height,width){
this.height = height
this.width = width
this.getHeight = function(){
return this.height
}
}
Reactangle.prototype.getArea = function(){
return this.height * this.width
}
function triangle(height,width,color){
Reactangle.call(this,height,width)
this.color = color
}
function inherit(Sub,Super){
Object.setPrototypeOf(Sub.prototype,Super.prototype); // Sub 的实例继承 Super 的原型和方法
//Object.setPrototypeOf(Sub,Super); //使子类 Sub 指向父类 Super,第二条原型链
}
inherit(triangle,Reactangle)
triangle.prototype.getArea = function(){
return Reactangle.prototype.getArea.call(this)/2
}