gpt4 book ai didi

javascript - 从 Redux reducer 中的对象复制原型(prototype)函数

转载 作者:太空宇宙 更新时间:2023-11-04 15:28:49 25 4
gpt4 key购买 nike

case "CONNECTOR_CONNECTION_FULFILLED":
state = {
...state,
appState: 'loggedIn'
};
state.ourPlayer = { ...action.payload.player }

break;

因此,当我的应用程序触发此操作时,它会创建一个播放器对象供我的应用程序使用。玩家对象具有原型(prototype)方法(player.spawn()、player.killed()等),当我以这种方式复制它时,这些方法不会被复制。

最佳答案

{ ...someObject } 对象扩展语法以及 Object.assign 方法仅复制对象自己的可枚举属性。不可枚举的 props、原型(prototype) props 和原型(prototype)本身都不会被复制。

因此,虽然在 Redux 世界中不推荐这样做,但您可以为域对象创建某种复制构造函数,例如:

class Player {
constructor(anotherPlayer) {
// copy the props of another player there
}
}

并在 reducer 中使用它:

case "CONNECTOR_CONNECTION_FULFILLED":
state = {
...state,
appState: 'loggedIn',
};
state.ourPlayer = new Player(action.payload.player)

break;

关于javascript - 从 Redux reducer 中的对象复制原型(prototype)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44975643/

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