ES6 Class 的原生写法

解析 ES6 的 Class

工作中一直专注于写业务逻辑,猛然发现原生 JS 基础没怎么提升。Later better than never ,最近又去翻看高程3(红宝石书),果然知识就是推翻旧有体系搭建新的过程。

以前写过一篇文章浅显的讲了讲 JS 中 Class 的发展历程,以及简单的继承
Javascript之class的前世今生,主要看看里面画的两张原型链继承图),
今天打算通过我新的知识体系,深入 ES6 的 Class

创建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 方法内就是在定义构造函数内的属性和方法

Class 的继承

有了类的创建,肯定也要讲讲类的继承

创建一个类 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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值