Как в javascript передать значение из одного класса в другой в ООП?
Чтобы лучше понять реализацию ООП, я стараюсь разобраться на практическом примере.
Пытаюсь передать значение из класса GamePlay
в класс View
.
В draw_cell(cellIdx)
console.log
выводит newVal = undefined
.
Хотелось бы, чтобы newVal
присвоилось значение переменной let value = 77;
Код:
const GamePlay = (function create_game_play() {
let game = create_game();
function create_game() {
let value = 77;
console.log('value = ' + value);
let game = {
}
return game
}
function start_game() {
View.render_start_game(game);
}
var game_play = {
game: game,
start_game() { start_game() },
}
return game_play
})();
const View = (function create_view() {
let newVal = null;
let cellIdx = 0;
console.log('newVal = ' + newVal);
function draw_cell(cellIdx) {
newVal = cellIdx.value;
console.log('newVal = ' + newVal);
}
function render_start_game(game) {
draw_cell(cellIdx);
}
return {
render_start_game: render_start_game,
}
})();
GamePlay.start_game()
Ответы (1 шт):
Автор решения: bgn15
→ Ссылка
Я смог передать значение из функции GamePlay
в функцию View
.
console.log
выводит newVal = 333
.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My_QUESTION</title>
</head>
<body>
<h1>My_QUESTION.</h1>
<script>
const GamePlay = (function create_game_play() {
let VAL_01 = 77;
let game = create_game();
function create_game() {
VAL_01 = 333;
console.log('VAL_01 = ' + VAL_01);
let game = {
}
return game
}
function start_game() {
View.render_start_game(game);
}
var game_play = {
game: game,
start_game() { start_game() },
get VAL_01() { return VAL_01 },
}
return game_play
})();
const View = (function create_view() {
let newVal = null;
let cellIdx = 0;
console.log('newVal = ' + newVal);
newVal = GamePlay.VAL_01;
console.log('newVal = ' + newVal);
function draw_cell(cellIdx) {
console.log('function draw_cell --- newVal = ' + newVal);
}
function render_start_game(game) {
draw_cell(cellIdx);
}
return {
render_start_game: render_start_game,
}
})();
GamePlay.start_game()
</script>
</body>
</html>