gpt4 book ai didi

javascript - 无法在构造函数原型(prototype)中调用 'this'

转载 作者:行者123 更新时间:2023-11-28 00:00:20 25 4
gpt4 key购买 nike

我无法弄清楚为什么我无法在 Game 构造函数的原型(prototype)中使用“this.count”而不会出现 NaN 或未定义。每当用户正确回答四个问题之一时,我就用它来跟踪分数。

我曾假设,一旦在构造函数中声明了一个属性,它就可以在其任何原型(prototype)中使用?预先感谢您。

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();

最佳答案

在匿名函数内部,“this”引用的是匿名函数本身,而不是 Game。添加:

    var self = this;

在 .click(...) 之前并将“this”替换为“self”。

关于javascript - 无法在构造函数原型(prototype)中调用 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31865304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com