【问题标题】:Javascript Member Functions Out of ScopeJavascript 成员函数超出范围
【发布时间】:2010-11-22 17:21:25
【问题描述】:

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

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

}

我怎样才能完成这项工作?

【问题讨论】:

    标签: javascript oop scope


    【解决方案1】:

    看起来你只需要摆脱“这个”。在 add_button() 前面

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

    只需使用:

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

    【讨论】:

    • +1。希望他不需要 add_button 中的 this 指针的值,但这是一颗好星。
    【解决方案2】:

    “this.add_button();”中的“this”如果我没记错的话,实际上是指没有“add_button()”功能的锚元素本身。

    也许这会起作用:

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

    【讨论】:

      【解决方案3】:

      它不起作用的原因是thisonclick 函数的上下文中与thisn 函数/“类”的上下文中不同。如果您希望函数中的this 等价于类中的this,您需要将this 绑定 到该函数。

      绑定是一种改变函数作用域的方法——本质上,如果你绑定到一个函数,你就是将this变量替换为指向别的东西。您可以在this alternateidea article 中阅读有关 Javascript 绑定的更多信息。

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

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

      这会将nthis 类绑定到 onclick 函数,从而产生您想要的效果。

      【讨论】:

        猜你喜欢
        • 2018-03-30
        • 1970-01-01
        • 1970-01-01
        • 2018-07-21
        • 2013-04-20
        • 1970-01-01
        • 2017-10-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多