代码之家  ›  专栏  ›  技术社区  ›  Ian Baget

javascript成员函数超出范围

  •  1
  • Ian Baget  · 技术社区  · 16 年前

    我有一个类来创建锚定对象。当用户单击锚时,我希望它从父类运行一个函数。

    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()
        {
            ...
        }
    
    }
    

    我该怎么做?

    3 回复  |  直到 16 年前
        1
  •  5
  •   LorenVS    16 年前

    看起来你只需要去掉“这个”。在“添加”按钮()前面

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

    只需使用:

    a.onclick = function(){add_button();}
    
        2
  •  1
  •   Daniel Vandersluis    16 年前

    它不起作用的原因是 this onclick 函数与 n 函数/“class”。如果你想要 在要等效的函数内 在课堂上,你需要 绑定 到函数。

    绑定是一种改变函数作用域的方法——本质上,如果绑定到一个函数,则将替换 变量指向其他对象。您可以在 this alternateidea article .

    如果你在使用 prototype 例如,您可以执行以下操作:

    function n()
    {
        var make = function()
        {
            ...
            a.onclick = function() { this.add_button() }.bind(this);
            ...
        }
    }
    

    它可以绑定类 N号 到onclick函数,从而产生您想要的效果。

        3
  •  0
  •   Joe D    16 年前

    “this.add button();”中的“this”实际上是指锚点元素本身,如果我没有弄错的话,它没有“add button()”函数。

    也许这会奏效:

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