ES6类静态方法的this绑定到类本身,为何运行返回NaN?
问题根源
constructor 构造函数仅在使用 new 关键字生成类的实例时才会执行,构造函数内的 this 指向新生成的实例对象,而非类本身。你代码里的 width、height 都是挂载在实例上的属性,Circle 类自身并没有这两个属性,静态方法执行时 this.width 和 this.height 取值都是 undefined,undefined * undefined 自然返回 NaN。
解决方案
有两种符合你预期的写法,按需选择:
- 方案1:保留静态方法,将宽高定义为类的静态属性
class Circle { // 静态属性直接挂载到类本身,静态方法内的this可以直接访问 static width = 2; static height = 3; static area() { return this.width * this.height } } console.log(Circle.area()) // 输出6
- 方案2:宽高保持定义在实例上,将area改为实例方法
class Circle { constructor() { this.width = 2; this.height = 3; } // 去掉static修饰符,变为实例方法 area() { return this.width * this.height } } // 先实例化再调用方法 const circle = new Circle() console.log(circle.area()) // 输出6
内容的提问来源于stack exchange,提问作者Intaek
相关产品推荐
相关产品推荐

