我有一个对象State().score
,当在Handler().addToScore()
中被调用时,应该使用它的附加值进行更新。问题是它始终保持在初始值0
上。
const DOM = () => {
const dom = {}
dom.score = document.getElementsByClassName('score')[0]
return dom
}
const State = () => {
const state = {}
state.score = 0 // This remains 0, I want it to update when adding to it
return state
}
const Handler = () => {
const handler = {}
handler.addToScore = function() {
State().score += 10
console.log(State().score) // Equals to 0 on every click and never gets updated
DOM().score.innerHTML = State().score
}
return handler
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
function statusChangeCallback(response) {
if(response.status === 'connected') {
console.log( 'Logged in and authenticated' )
Handler().addToScore()
} else {
console.log('Not authenticated')
}
}
答案 0 :(得分:2)
每次运行State()
时,它都会设置返回一个score
为0
的新鲜对象
如果要保存State().score
的初始化结果,则必须保存。或者,您可以使用score
ter和get
ter
set
的方式
const State = () => {
const state = {}
state.score = 0 // This remains 0, I want it to update when adding to it
return state
}
console.log(State().score); // State() is a function that ALWAYS returns { score: 0 }
let savedScore = State().score;
savedScore += 1;
console.log(savedScore);
使用get
/ set
的示例(执行此操作的方法有多种:
https://jsfiddle.net/mswilson4040/1ds8mbqw/3/
class State {
constructor() {
this._score = 0;
}
get score() {
return this._score;
}
set score(val) {
this._score = val;
}
}
const state = new State();
console.log(state.score);
state.score += 1;
console.log(state.score);
当然,还有另一种方法可以使State
不起作用。看来您实际上是在尝试管理分数或状态,因此让State
成为最终每次都为您提供全新状态(分数)的功能都是不可能的。
像没有State
这样的函数那样简单的事情也可以工作:
const State = () => {
const state = {}
state.score = 0 // This remains 0, I want it to update when adding to it
return state
}
应该是
const State = {
score: 0
};