语法
基本语法
class ClassName {constructor(){ //constructor不是必须的//声明类的变量的地方...}//声明方法method1(){ ... }method2(){ ... }method3(){ ... }}
例子:
class Animal {constructor(name){this.name = name}sayName(){console.log("名字叫做:", this.name)}}//使用const Dog = new Animal("旺财");Dog.sayName() //名字叫做: 旺财
:::info 代码风格:
- 声明类名的时候,第一个字母大写。 :::
getter/setter
用法:
class Animal {constructor(name){this.name = name}//读取name的时候触发get方法get name(){return this._name}//赋值name的时候触发set方法set name(value){this._name = valueconsole.log("set触发了")}}//使用let dog = new Animal("旺财") //set触发了Dog.name //get触发了
:::warning 坑:
- 上面例子,在get/set一个属性的时候,如果没有在get里返回值,那么人为的去读取操作(console.log)那个属性,会得到
undefing:::
类继承
详见:js继承
类的静态属性与静态方法
new过程
上面的例子,当new一个对象时,就会创建一个名为Dog(取决于开发者想起什么名字)的新对象,constroctor对这个对象分配键值,对象的原型指向该类,因此可以直接调用这个类的方法。
调用类方法的这个过程就很像是Dog.prototype.sayName一样:
function Animal(name){this.name = name}Animal.prototype.sayName = function(){console.log("名字叫做:", this.name)console.log(this.name)}//用法const Dog = new Animal("旺财")Dog.sayName() //名字叫做: 旺财Dog.sayName()
因为得到的结果与使用类的结果基本相同,因此可以说类是prototype的语法糖也不为过。
类的特点
- 与prototype不同,类会在创建函数的时候在内部标记
[[IsClassConstructor]]: true,JS会检查该语法,必须使用new来调用。 - 类方法不可枚举。类默认将pototype的所有方法的
enumerable标志设置为false(不明白这是什么请了解:属性标志和属性描述符) - 使用类,将会自动进入严格模式,即默认使用
use strict。
