【发布时间】: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