gpt4 book ai didi

javascript - 链接到按钮的原型(prototype)功能不起作用

转载 作者:行者123 更新时间:2023-11-29 16:54:14 25 4
gpt4 key购买 nike

我有一个类(我想这就是所谓的)并在我的代码中创建了一个名为 peter 的对象。我现在想按如下方式升级 Peter:

// Define the class
function character(name, level){
this.name = name;
this.level = level;
}

// Create Peter at level 1
var peter = new character("Peter", 1);

// This will display the name of the character, level and a button to level him up
character.prototype.display = function() {
document.getElementById("name").innerHTML += this.name;
document.getElementById("level").innerHTML += this.level;

// This line calls `levelup()` on load which is not what I want
// and clicking the button no more calls `levelup`!
document.getElementById("levelupbutton").onclick = this.levelup();

// This line would call the function on click, but it looks like `this`
// is not being passed down to the function `levelup` so I get NaN on
// this.level down below?
//document.getElementById("levelupbutton").onclick = this.levelup;
};


character.prototype.levelup = function() {
alert("Level up in progress!");
this.level++;
alert(this.level);
}

peter.display();

jsfilldle

我可能错误地调用了该函数,而且我似乎无法弄清楚如何正确地调用它。谁能给我一些指示?我是 OOP 的新手,所以如果解决方案涉及 OOP 的东西,你能尽量解释一下吗?

最佳答案

您需要将其绑定(bind)levelup,而不是在线调用它以获得您想要的行为。 Updated your fiddle并给出正确答案。

levelupbutton.onclick = this.levelup.bind(this);

function character(name, level){
this.name = name;
this.level = level;
}
var peter = new character("Peter", 1); // Instantiate new objects with 'new'
character.prototype.display = function(){
document.getElementById("name").innerHTML += this.name;
document.getElementById("level").innerHTML += this.level;
document.getElementById("levelupbutton").onclick = this.levelup.bind(this);
};
character.prototype.levelup = function(){
alert("Level up in progress!");
this.level++;
alert(this.level);
}
peter.display();
<span>Character Name:</span> <span id="name"></span><br />
<span>Character Level:</span> <span id="level"></span><br />
<button id="levelupbutton">Level Up!</button>

关于javascript - 链接到按钮的原型(prototype)功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33583922/

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