class Point{
constructor(x, y) { this.x = x; this.y = y; } toString() { return '(' + this.x + ', ' + this.y + ')'; }
}
定义“类”的方法的时候,前面不需要加上function
这个关键字,直接把函数定义放进去了就可以了。另外,方法之间不需要逗号分隔,加了会报错,类的方法都是写入在phototype中的,
class Bar {
doStuff() { console.log('stuff'); } } var b = new Bar(); b.doStuff() // "stuff" 调用类的方法,也是直接对类使用new
命令,跟构造函数的用法完全一致。
class Point {
constructor() { // ... } toString() { // ... } toValue() { // ... } } // 等同于 Point.prototype = { constructor() {}, toString() {}, toValue() {}, };
Object.assign
方法可以很方便地一次向类添加多个方法。
class Point {
constructor(){ // ... } } Object.assign(Point.prototype, { toString(){}, toValue(){} });