gpt4 book ai didi

Javascript 成员函数超出范围

转载 作者:行者123 更新时间:2023-11-30 08:17:06 25 4
gpt4 key购买 nike

我有一个创建 anchor 对象的类。当用户点击 anchor 时,我希望它从父类运行一个函数。

function n()
{
var make = function()
{
...

var a = document.createElement('a');
a.innerHTML = 'Add';
//this next line does not work, it returns the error:
//"this.add_button is not a function"
a.onclick = function() { this.add_button(); }

...
}

var add_button = function()
{
...
}

}

我怎样才能完成这件事?

最佳答案

看来您只需要去掉“this”即可。在 add_button() 前面

您将 add_button 声明为局部变量(或者以 javascript 类工作的奇怪方式声明为私有(private)),因此它实际上不是“this”的成员。

只需使用:

a.onclick = function(){add_button();}

关于Javascript 成员函数超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1329819/

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