gpt4 book ai didi

javascript - 如何在对象函数中引用对象数据?

转载 作者:行者123 更新时间:2023-11-28 17:04:22 25 4
gpt4 key购买 nike

我正在尝试制作一个简单的井字游戏来学习和练习 JavaScript OOP,但遇到了一些困难。

我想引用game.turn触发 game.handleClick 时的值功能。我知道使用 this关键字引用被调用事物的范围,在 handleClick 中,thisgame-tile-x被点击。如何引用“handleClick”函数范围之外的对象值?

任何帮助将不胜感激!

<div id="game-board">
<div id="game-tile-1" class="game-tile"></div>
<!-- divs 2-8 -->
<div id="game-tile-9" class="game-tile"></div>
</div>
function Game() {
this.tiles = document.getElementsByClassName('game-tile'),
this.turn = 0;

this.init = function() {
for (let i = 0; i < this.tiles.length; i++) {
// reset game tiles
this.tiles[i].innerHTML = '';

// setup event listeners
this.tiles[i].addEventListener('click', this.handleClick);
}
};
this.handleClick = function() {
let id = parseInt(this.id.replace('game-tile-', ''));
console.log(id); // returns 0, 1, 2, etc.
console.log(this.turn); // returns undefined
};
}

let game = new Game();
game.init();

最佳答案

这是一个基本的解决方案

function Game() {
this.tiles = document.getElementsByClassName('game-tile'),
this.turn = 0;

this.init = function() {
let tile;
for (let i = 0; i < this.tiles.length; i++) {
tile = this.tiles[i];
// reset game tiles
tile.innerHTML = '';

// setup event listeners
// don't mix this for the node & this for the game
// let's bind the context to the game, and the first param to the tile
tile.addEventListener('click', handleClick.bind(this, tile));
}
};

function handleClick(tile) {
let id = parseInt(tile.id.replace('game-tile-', ''));
console.log(id); // returns 0, 1, 2, etc.
console.log(this.turn); // returns undefined
};
}

let game = new Game();
game.init();

关于javascript - 如何在对象函数中引用对象数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56264956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com