【问题标题】:Question Regarding some Haverbeke "Eloquent JavaScript" Constructor Code关于一些 Haverbeke “Eloquent JavaScript” 构造函数代码的问题
【发布时间】:2021-03-29 01:17:26
【问题描述】:

我有点难以理解 Marijn Haverbeke 的“Eloquent JavaScript”一书第 108 页的几行代码。

也就是说,在下面的示例中,当 Matrix 对象被实例化时,我不明白构造函数参数列表中的“element = (x, y) => undefined”在做什么"让矩阵 = new Matrix(3, 3, (x, y) => value ${x}, ${y});"

可以帮我一步一步吗?似乎我们正在将一个函数传递给构造函数,但我不明白为什么构造函数参数列表的设置方式与另一个箭头函数一样。

var Matrix = class Matrix {
  constructor(width, height, element = (x, y) => undefined) {
    this.width = width;
    this.height = height;
    this.content = [];

    for (let y = 0; y < height; y++) {
      for (let x = 0; x < width; x++) {
        this.content[y * width + x] = element(x, y);
      }
    }
  }

  get(x, y) {
    return this.content[y * this.width + x];
  }
  set(x, y, value) {
    this.content[y * this.width + x] = value;
  }
}

var MatrixIterator = class MatrixIterator {
  constructor(matrix) {
    this.x = 0;
    this.y = 0;
    this.matrix = matrix;
  }

  next() {
    if (this.y == this.matrix.height) return {done: true};

    let value = {x: this.x,
                 y: this.y,
                 value: this.matrix.get(this.x, this.y)};
    this.x++;
    if (this.x == this.matrix.width) {
      this.x = 0;
      this.y++;
    }
    return {value, done: false};
  }
}

Matrix.prototype[Symbol.iterator] = function() {
  return new MatrixIterator(this);
};

let matrix = new Matrix(3, 3, (x, y) => `value ${x}, ${y}`);
for (let {x, y, value} of matrix) {
  console.log(x, y, value);
}

【问题讨论】:

    标签: javascript class constructor instantiation arrow-functions


    【解决方案1】:

    好的,如果参数丢失或未定义,我忘记了在 ES6+ 参数后面的等号是默认值。他这样做的方式有点尴尬。

    【讨论】:

      猜你喜欢
      • 2012-08-19
      • 1970-01-01
      • 2014-06-13
      • 2011-06-08
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多