gpt4 book ai didi

javascript - 如何在函数中调用变量?

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

请引用以下代码,

var XClass = function () {
this.dataMember = "hello world";

$("div").on("click", "button", function() {
console.log(this.dataMember); //error
});

}

如何在 on 函数中访问 this.dataMember?我用谷歌搜索了 js 的新内容。

最佳答案

尝试将 this 分配给变量:

var XClass = function () {
var that = this;
this.dataMember = "hello world";

$("div").on("click", "button", function() {
console.log(that.dataMember);
});
}

这样,that 将引用当前的 XClass 对象。否则,在事件处理程序回调中,this 指的是被单击的对象。

关于javascript - 如何在函数中调用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29161723/

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