JavaScript. Можно ли использовать методы класса в его конструкторе?
В таком коде интерпретатор жалуеться, что "elementFromChar" undefined. Почему?
class World {
elementFromChar(legend, ch) {
if (ch == " ")
return null;
let element = new legend[ch]();
element.originChar = ch;
return element;
}
constructor(map, legend) {
let grid = new Grid(map[0].length, map.length);
this.grid = grid;
this.legend = legend;
map.forEach(function(line, y) {
for (let x = 0; x < line.length; x++)
grid.set(new Vector(x, y),
elementFromChar(legend, line[x]));
});
}
}
Так же в строке grid.set(...) если написать this.grid.set пишет "Cannot read property 'grid' of undefined". Почему и что делать?
Ответы (1 шт):
Автор решения: ZX-SPECTRUM
→ Ссылка
- Действительно забыл указать this перед функцией
- функция перекрывает this своим this, нужно использовать стрелочную функцию или bind()