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