对象中声明的函数不是函数

时间:2019-01-23 22:20:09

标签: javascript function javascript-objects

我有一个对象,里面有一个称为Handler.addToScore()的方法。调用此方法时,我收到一条错误消息,指出它不是函数。我不知道这里有什么问题。

const DOM = () => {
  const dom = {}

  dom.score = document.getElementsByClassName('score')[0]

  return dom
}

const State = () => {
  const state = {}

  state.score = 0
  state.isLoggedIn.facebook = 0
  state.isLoggedIn.linkedin = 0

  return state
}

const Handler = () => {
  const handler = {}

  handler.addToScore = function() { 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')
  }
}

2 个答案:

答案 0 :(得分:3)

将行更改为

function statusChangeCallback(response) {
  if (response.status === "connected") {
    console.log("Logged in and authenticated");
    Handler().addToScore(); // see comment, Handler is a function. 
  } else {
    console.log("Not authenticated");
  }
}

答案 1 :(得分:2)

您需要在调用addToScore方法之前运行函数Handler

Handler().addToScore();