I am having a hard time understanding the following class declaration: it seems that element
is default to undefined
, but I have no idea why
(x, y)
in the element = (x,y) => undefined
necessary; is (x,y)
a abbreviated way of specifying array elements inside element
object?element(x, y)
to access array elements inside element
?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);
}
}
}
let matrix = new Matrix(2, 2, (x, y) => `value ${x},${y}`);
The code is from Chapter 6 of Eloquent JS booke
element
is being set to an arrow function expression that takes two arguments and returns undefined
. This code would be equivalent:
constructor (width, height, element) {
if (!element) element = (x, y) => undefined
}
And these two are mostly equivalent with the scope caveat (this
in the version with the function
keyword refers to that function):
(x, y) => undefined
function (x, y) { return undefined }
Either way it's written, element
is a function that, by default (if no third parameter is passed when instantiating an instance of that class), will take two parameters x
and y
and return undefined
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments