javascript对象未更新为附加值

时间:2019-01-24 00:19:07

标签: javascript javascript-objects

我有一个对象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')
  }
}

1 个答案:

答案 0 :(得分:2)

每次运行State()时,它都会设置返回一个score0的新鲜对象

如果要保存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
};