Ian*_*Ian 1 javascript oop scope
我有一个创建锚对象的类.当用户点击锚时,我希望它从父类运行一个函数.
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()
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
我怎么能这样做?
看起来你只需要摆脱"这个".在add_button()前面
您将add_button声明为局部变量(或以javascript类工作的奇怪方式私有),因此它实际上不是"this"的成员.
只需使用:
a.onclick = function(){add_button();}
Run Code Online (Sandbox Code Playgroud)