背景
class的出现,让js开发者告别了使用原型对象模仿面向对象中的类和类继承时代。在前端开发中,使用到class的地方非常之多,所以掌握class的用法已经必不可少了。
划重点
JS 中并没有一个真正的 class 原始类型, class 仅仅只是对原型对象运用语法糖(PS:什么是语法糖?就是不用写原始方法,而是提供了一种简单的写法,底层还是原始的方法)。所以,只有理解如何使用原型对象实现类和类继承,才能真正地用好 class。【关于使用原型对象实现类和类继承详解,后续持续更新】
来看一个class的例子
先记一个知识点:class里面可以写 三种 方法,第一种是constructor内部的方法,第二种是原型链上的方法,第三种是static函数静态方法。
class Person{
constructor(name) {
this.name = name;
// constructor内部的方法,在 new 一个实例的时候就会生命这个方法,一般情况下也是在内部调用的
function hello1() {
console.log(`hello1 ${name}, this is an inner function!`)
}
hello1()
}
hello2() {
console.log(`hello2 ${this.name}, this is a prototype function!`);
}
// 静态方法,不需要new就可以调用
static hello3() {
// 这里的 this.name 返回的是class的名字
console.log(`hello3 ${this.name}, this is a static function!`);
}
}
const p = new Person('orchid');
// 结果: hello1 orchid, this is an inner function!
p.hello2();
// 结果: hello2 orchid, this is a prototype function!
Person.hello3();
// 结果: hello3 Person, this is a static function!
对应的原型对象实现
function Person(name) {
this.name = name;
// 与上面的 hello1 对应
function hello1() {
console.log(`hello1 ${name}, this is an inner function!`)
}
hello1();
}
// 与上面的 hello2 对应
Person.prototype.hello2 = function() {
console.log(`hello2 ${this.name}, this is a prototype function!`);
}
// 与上面的 static 方法 hello3 对应
Person.hello3 = function() {
console.log(`hello3 ${this.name}, this is a static function!`);
}
const p = new Person('orchid');
// 结果: hello1 orchid, this is an inner function!
p.hello2();
// 结果: hello2 orchid, this is a prototype function!
Person.hello3();
// 结果: hello3 Person, this is a static function!
相信你通过上面的例子已经知道了为什么说class只是一种语法糖了,代码的确是简单而且容易阅读了。
上面就是一个将es6转化为原型对象的代码实现。es6其实就是将class语法转成了原型对象实现,底部还是原型对象的代码。其实class就是一个函数而已。