不能在构造函数的原型中调用'this'

时间:2015-08-06 20:35:58

标签: javascript inheritance constructor prototype

我无法弄清楚为什么我无法在我的游戏构造函数的原型中使用'this.count'而没有获得NaN或未定义。每当用户正确回答四个问题中的一个时,我就用它来跟踪点数。

我曾假设一旦在构造函数中声明了一个属性,它可以在任何原型中使用吗?提前谢谢。

var questions = [
  {question: "What programming language does the library 'jQuery' belongs to?",
  answer: "JAVASCRIPT"},
  {question: "What programming language does 'Sass' builds upon?",
  answer: "CSS"},
  {question: "How do you abbreviate Hyper Text Markup Language?",
  answer: "HTML"},
  {question: "What company does the framework 'Bootstrap' belong to?",
  answer: "TWITTER"}
];

var Game = function(array) {
  this.array = array;
  this.count = 0;   // this.count is set to 0 //
}

var guess = new Game(questions);

Game.prototype.play = function() {
  console.dir(this.array);
  console.dir(this.count);
  $('button').click(function() {
    for (var i = 0; i < this.array.length; i++) {
        var newGuess = prompt(this.array[i].question).toUpperCase();
        if (newGuess === this.array[i].answer) {
            ++this.count;    // Problem happens here //
            console.log(this.count);
        } else {
            alert('Incorrect.');
        }
    }
    alert('You answered ' + this.count + ' out of 4 correct.');
  });
}
guess.play();

2 个答案:

答案 0 :(得分:1)

在匿名功能内部,这个&#39;引用匿名函数本身,而不是游戏。添加:

    var self = this;
在.click(...)之前

并替换&#39;这个&#39;与&#39; self&#39;。

答案 1 :(得分:0)

这是因为你所指的是点击处理函数的这个,它不包含计数:

解决方案1 ​​ - 此别名:

Game.prototype.play = function() {
var that = this; // the alias

  console.dir(this.array);
  console.dir(this.count);
  $('button').click(function() {
    for (var i = 0; i < this.array.length; i++) {
        var newGuess = prompt(this.array[i].question).toUpperCase();
        if (newGuess === this.array[i].answer) {
            ++this.count;    // Problem happens here //
            console.log(this.count);
        } else {
            alert('Incorrect.');
        }
    }
    alert('You answered ' + that.count + ' out of 4 correct.'); // using the alias
  });
}

解决方案2 - 使用bind来改变它:

  $('button').click(function() {
    for (var i = 0; i < this.array.length; i++) {
        var newGuess = prompt(this.array[i].question).toUpperCase();
        if (newGuess === this.array[i].answer) {
            ++this.count;    // Problem happens here //
            console.log(this.count);
        } else {
            alert('Incorrect.');
        }
    }
    alert('You answered ' + this.count + ' out of 4 correct.');
  }.bind(this)); // the this of the outer closure is now the this of the click handler function