Why doesn#39;t my closure function want to reassign its parent function variable, when within an if statment?(为什么我的闭包函数不想在IF语句中重新赋值其父函数变量?)
问题描述
我已经创建了用于描述游戏逻辑的工厂函数。我使用内部函数在游戏中切换玩家。问题是,当我试图从内部函数中重新分配当前球员时,它不起作用。当前的玩家永远不会改变。我想这是关于结束的事情,我并不是真的理解。你能给我解释一下我错过了什么吗?下面是我正在编写的一段代码:
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;
推荐答案
您的代码返回 您需要使用如下函数返回值。currentPlayer
的值,该值在原始对象的属性更新时不会更新。因此,闭包运行得很好,但事实是您的返回值并没有指向更新后的对象,它只是一个新值,在return
语句时将保持不变。
let 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;
};
const getCurrentPlayer = () => currentPlayer;
return {
currentPlayer,
switchPlayers,
getCurrentPlayer
};
})();
game.switchPlayers();
console.log(game.currentPlayer);
console.log(game.getCurrentPlayer());
或只需在函数的this
指针上定义属性currentPlayer
,然后将其用作类型(使用new
关键字),如下所示。
function GameType() {
let player1 = "Jim";
let player2 = "Mary";
this.currentPlayer = player1;
this.switchPlayers = () => { //This closure function is supposed to reassign the value of currentPlayer above. But it does not do it.
if (this.currentPlayer === player1) {
this.currentPlayer = player2;
} else {
this.currentPlayer = player1;
}
return this.currentPlayer;
};
}
let game = new GameType();
console.log(game.currentPlayer);
game.switchPlayers();
console.log(game.currentPlayer);
这篇关于为什么我的闭包函数不想在IF语句中重新赋值其父函数变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我的闭包函数不想在IF语句中重新赋值其父


基础教程推荐
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01