Class 的基本语法

ES5写法

  1. function Point(x,y){
  2. this.x = x
  3. this.y = y
  4. }
  5. Point.prototype.toString = function(){
  6. return `${this.x} + ${this.x}`
  7. }
  8. var p = new Point(1,2)
  9. console.log(p)
  10. console.log(p.toString())

ES6

  1. class Point{
  2. constructor(x,y){
  3. this.x = x;
  4. this.y = y
  5. }
  6. toString(){
  7. return `${this.x} + ${this.x}`
  8. }
  9. }

constructor 方法
image.png

解构赋值

用途

交换变量的值

  1. let x = 1;
  2. let y = 2;
  3. [x, y] = [y, x];

从函数返回多个值

  1. // 返回一个数组
  2. function example() {
  3. return [1, 2, 3];
  4. }
  5. let [a, b, c] = example();
  6. // 返回一个对象
  7. function example() {
  8. return {
  9. foo: 1,
  10. bar: 2
  11. };
  12. }
  13. let { foo, bar } = example();

提取JSON数据

  1. let jsonData = {
  2. id: 42,
  3. status: "OK",
  4. data: [867, 5309]
  5. };
  6. let { id, status, data: number } = jsonData;
  7. console.log(id, status, number);
  8. // 42, "OK", [867, 5309]

函数参数的默认值

  1. jQuery.ajax = function (url, {
  2. async = true,
  3. beforeSend = function () {},
  4. cache = true,
  5. complete = function () {},
  6. crossDomain = false,
  7. global = true,
  8. // ... more config
  9. } = {}) {
  10. // ... do stuff
  11. };

指定参数的默认值,就避免了在函数体内部再写var foo = config.foo || 'default foo';这样的语句。

输入模块的指定方法

指定输入哪些方法

  1. const { SourceMapConsumer, SourceNode } = require("source-map");