js模拟实现ES6的类和继承

ES6的类实际上仍然是构造函数,就是一个语法糖,我们可以模拟实现一下

理解类

function Person(name, age) {
	this.name = name
	this.age = age
	this.laugh = function() {
		console.log('haha')
	}
}

Person是一个构造函数,我们可以利用它创造多个Person对象

const p1 = new Person('zs', 18)
const p2 = new Person('ls', 19)
p1.name // 'zs'
p2.age // 19
p1.laugh() // 'haha'

但这样有一个问题,多个Person对象的属性确实是难找到共性的,但它们的方法是相同的,创建每个对象都要新创建一个相同的方法,浪费了性能

所以我们通常在构造函数的prototype上添加方法,改造为

function Person(name, age) {
	this.name = name
	this.age = gae
}
Person.prototype.laugh = function() {
	console.log('haha')
}

实际上类就是这样处理的

class Person {
	constructor(name, age) {
		this.name = name
		this.age = age
	}
	laugh() {
		console.log('haha')
	}
}
const p = new Person('zs', 18)

我们可以在浏览器中看一下Person实例p
在这里插入图片描述
可以看到在p的__proto__对象上找到了laugh方法,验证了上述所说

模拟继承

我们知道在ES6的类中,有extends(继承)的语法
子类能够继承父类所有的属性和方法

  • 属性的继承
function Father(arg1, arg2) {
	this.arg1 = arg1
	this.arg2 = arg2
}

// 利用Function.prototype.call方法,子类调用父类的构造函数
function Son(arg1, arg2, arg3) {
	Father.call(this, arg1, arg2)
	this.arg3 = arg3
}

const son = new Son(1, 2, 3)
  • 方法的继承
function Father(arg1, arg2) {
	this.arg1 = arg1
	this.arg2 = arg2
}
Father.prototype.laugh = function() {
	console.log('haha')
}

function Son(arg1, arg2, arg3) {
	Father.call(this, arg1, arg2)
	this.arg3 = arg3
}
// 让Son的原型对象指向Father对象,如此Son的实例就能在原型链上找到Father的方法
Son.protoype = new Father()
// 添加constructor
Son.prototype.constructor = Son
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值