ES6 语法四(部分)

246 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

摘要

ES6 是 ECMAScript 6.0 的简称,是 JavaScript 语言的下一代标准。ECMAScript 和 JavaScript 的关系是,前者是后者的规格,后者是前者的一种实现。

Class 的基本语法

ES6 以前写法
function Point(x, y) {
    this.x = x
    this.y = y
}

Point.prototype.toString() {
    return '(' + this.x + ', ' + this.y + ')'
}

var p = new Point(1, 2)
ES6 写法
class Point {
    constructor(x, y) {
        this.x = x
        this.y = y
    }
    
    toString() {
        return '(' + this.x + ', ' + this.y + ')'
    }
}

constructor() 是构造方法,this 代表实例对象

类的所有方法都定义在类的 prototype 属性上面

class Point {
    constructor() {}
    
    toString() {}
    
    toValue() {}
}

// 等同于
Point.prototype = {
    constructor() {},
    toString() {},
    toValue() {}
}

constructor 方法

constructor() 是类的默认方法,生成对象实例时自动调用该方法。一个类必须有 constructor() 方法,如果没有显式定义,一个空的 constructor() 方法会被默认添加。

class Point {}

// 等同于
class Point {
  constructor() {}
}

类必须使用 new 调用,否则会报错。普通构造函数不用 new 也可以执行。

class Foo {
  constructor() {
    return Object.create(null);
  }
}

Foo()

image.png

属性表达式

类的属性名,可以采用表达式。

let methodName = 'getArea';

class Square {
  constructor() {}

  [methodName]() {}
}

上面代码中,Square 类的方法名 getArea,是从表达式得到的。

注意点

  • 不存在变量提升
new Foo()
class Foo {}

image.png

  • this 的指向

类的方法内部如果含有this,它默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能报错。

class Logger {
  printName(name = 'there') {
    this.print(`Hello ${name}`)
  }

  print(text) {
    console.log(text)
  }
}

const logger = new Logger()
const { printName } = logger
printName()