javascript类如何定义_ES6类语法如何使用?

12次阅读

es6 class必须用new调用,直接调用报错;子类constructor必须首行调用super();方法不可枚举且不绑定this;静态与实例方法可同名但需区分调用方式。

javascript类如何定义_ES6类语法如何使用?

class 声明必须用 new 调用,不能当普通函数执行

ES6 的 class 本质是语法糖,底层仍基于原型,但设计上强制要求使用 new。直接调用会报错:

class Person {   constructor(name) {     this.name = name;   } } Person('Alice'); // TypeError: Class constructor Person cannot be invoked without 'new'

这个限制能避免意外丢失 this,也和内置类(如 dateArray)行为一致。如果真需要“可选 new”的构造逻辑,得回退到传统函数 + arguments.Length 判断,但那就不是标准 class 了。

constructor 不写也会隐式存在,但继承时必须显式调用 super()

class Foo {} 等价于 class Foo { constructor() {} };但一旦子类 extends 父类,且定义了 constructor,就必须第一行写 super(),否则报错:

class Animal {   constructor(name) {     this.name = name;   } } class Dog extends Animal {   constructor(name, breed) {     // 必须写,否则 ReferenceError: Must call super constructor     super(name);     this.breed = breed;   } }

漏掉 super() 或调用位置不在首行,都会触发严格错误。注意:即使父类没有显式 constructor,子类的 constructor 里仍需 super() —— 因为隐式构造器也需要初始化 this

方法默认不可枚举,且不绑定 this,箭头函数写法要小心

class 内定义的普通方法(包括 constructor)会自动添加 enumerable: false 属性,所以 for...inObject.keys() 都遍历不到它们。另外,这些方法不会自动绑定 this

class Button {   constructor(label) {     this.label = label;   }   handleClick() {     console.log(this.label);   } } const btn = new Button('OK'); document.addEventListener('click', btn.handleClick); // this 指向 window 或 undefined(严格模式)

常见解法有三:

  • 事件绑定时用 btn.handleClick.bind(btn)
  • 在 constructor 中赋值:this.handleClick = this.handleClick.bind(this)
  • 用箭头函数声明方法:handleClick = () => { ... }(注意:这是类字段语法,需额外支持)

最后一种最简洁,但属于 ES2022 提案(目前主流环境已支持),不是原始 class 语法的一部分。

静态方法和实例方法不能同名,且 Static 方法无法被实例调用

class 中可以用 static 定义静态方法,它属于类本身,不属于实例:

class MathUtils {   static add(a, b) {     return a + b;   }   add(a, b) {     return a + b + 1;   } } MathUtils.add(1, 2); // 3(走静态方法) const m = new MathUtils(); m.add(1, 2); // 4(走实例方法)

但注意:静态方法和实例方法**可以同名**,js 引擎靠调用方式区分。不过这容易引发混淆,实际项目中应避免。另外,m.add() 能调用实例方法,但 m.constructor.add() 才能访问静态方法——别指望 m.add() 自动 fallback 到 static 版本。

text=ZqhQzanResources