我创建了这个工厂函数,用于描述游戏逻辑。我使用内部函数来切换游戏中的玩家。问题是,当我尝试从内部函数中重新分配当前玩家时,它不起作用。当前的玩家永远不会改变。我想这是关于封闭的一些事情,我并没有真正理解。你能向我解释一下我缺少什么吗?这是我正在处理的代码片段:
const game = (() => {
let player1 = "Jim";
let player2 = "Mary";
let currentPlayer = player1;
const switchPlayers = () => { //This closure function is supposed to reassign the value of currentPlayer above. But it does not do it.
if (currentPlayer === player1) {
currentPlayer = player2;
} else {
currentPlayer = player1;
}
return currentPlayer;
};
return {currentPlayer, switchPlayers};
})();
game.switchPlayers // works as needed and switches the players every time it is invoked but does not reassign the variable within its parent function;
game.currentPlayer // does not get reassigned, when switchPlayers function is invoked, and returns player1 as was assigned at the start;
It does重新分配变量。
问题是您返回的对象具有以下属性值的副本这些变量的引用,而不是对变量的引用。
So let currentPlayer
被改变了但是game.currentPlayer
仍然包含原始值的副本。
摆脱变量,只修改对象属性。
const game = (function() {
const player1 = "Jim";
const player2 = "Mary";
let o = {
currentPlayer: player1
};
const switchPlayers = () => {
if (o.currentPlayer === player1) {
o.currentPlayer = player2;
} else {
o.currentPlayer = player1;
}
return o.currentPlayer;
};
o.switchPlayers = switchPlayers;
return o;
})();
console.log(game.currentPlayer);
console.log(game.currentPlayer);
console.log(game.switchPlayers());
console.log(game.currentPlayer);
console.log(game.currentPlayer);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)