为什么我的代码不会调用该对象的此方法?

时间:2019-02-10 04:19:57

标签: javascript

body标签中有一个事件处理程序。

<body onload="hangmanGame.populateQuestions();">

应该获得数组的随机位置...

const hangmanGame = {
obtainRandom(x) {
    return Math.floor(Math.random() * Math.floor(x));
  },
populateQuestions() {
    let randNum = obtainRandom(5);
    let numToPopulate = stemQuestions[randNum];
    console.log(randNum);
    console.log(numToPopulate);
}, 
stemQuestions : ['What do roots of a quadratic equation represent in a parabola?',
                 'What is a chemical process where a solid turns into a gas without going through a liquid stage',
                 'What is the name of the peculiar kind of inheritance pertinent to JavaScript?',
                 'What is the product of mass and velocity?',
                 'What is acceleration with respect to velocity?'],
stemAnswers :  ['intercepts','sublimation','prototype','momentum','derivative']

}

但是根据控制台,这两个值都是不确定的... 你能给我一些见识吗?

1 个答案:

答案 0 :(得分:0)

obtainRandomstemQuestionshangmanGame的属性,因此,为了从populateQuestions内部引用它们,您需要使用this

populateQuestions() {
    let randNum = this.obtainRandom(5);
    let numToPopulate = this.stemQuestions[randNum];
    console.log(randNum);
    console.log(numToPopulate);
}