[英]Is it possible to access to a class instance that it is inside another class in JavaScript?
I was trying to access an object instantiated inside a class, but something isn't working.我试图访问在类中实例化的对象,但有些东西不起作用。
I have three classes: App, Map, Player我有三个类:应用程序、地图、播放器
App class instantiated map class应用类实例化地图类
class App { constructor(canvas, sizeX, sizeY, sizeCase) { this.map = new Map(canvas, sizeX, sizeY, sizeCase); } }
Map地图
Inside Map
class, is instantiated the Player
class.在
Map
类中,实例化了Player
类。 My main problem, is that I can´t access the instance of Player
to access to its methods我的主要问题是我无法访问
Player
的实例来访问它的方法
class Map { constructor(canvas, sizeX, sizeY, sizeCase) { this.canvas = document.getElementById("canvas"); this.canvas.width = sizeX * sizeCase; this.canvas.height = sizeY * sizeCase; this.size = { x: sizeX, y: sizeY, case: sizeCase }; } setPlayers(quantity) { for (let index = 0; index < quantity; index++) { let x = App.random(this.size.x); let y = App.random(this.size.y); if (this.mapGame[x][y] == 0) { switch (index) { case 0: let player1 = new Player("vampi", 100, y, x); break; case 1: let player2 = new Player("wolfi", 100, y, x); break; default: break; } }else { console.log("Position occupied"); index--; } } } }
Player播放器
class Player { constructor(name, score, positionY, positionX) { this.name = name; this.score = score; } drawPlayer(playerImage) { app.map.mapGame[this.y][this.x] = 2; } }
Most of the questions I have read here are related to java, and the javascript ones I have found, are not related to my question, or I didn´t find the relation after reading them.我在这里读到的大多数问题都与 java 相关,而我发现的 javascript 问题与我的问题无关,或者我在阅读它们后没有找到关系。
The console says:控制台说:
"TypeError: app.map.player1 is undefined"
“类型错误:app.map.player1 未定义”
Variables are not the same as class properties.变量与类属性不同。 To make
app.map.player1
work, you need to assign the property.要使
app.map.player1
工作,您需要分配该属性。
setPlayers(quantity) {
for (let index = 0; index < quantity; index++) {
let x = App.random(this.size.x);
let y = App.random(this.size.y);
if (this.mapGame[x][y] == 0) {
switch (index) {
case 0:
this.player1 = new Player("vampi", 100, y, x);
break;
case 1:
this.player2 = new Player("wolfi", 100, y, x);
break;
default:
break;
}
} else {
console.log("Position occupied");
index--;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.