【问题标题】:JavaScript: call of function with 'this.' does not reference to method in classJavaScript:使用“this”调用函数。不引用类中的方法
【发布时间】:2012-02-11 12:36:59
【问题描述】:

这是一个抽象的 JavaScript 代码示例,说明了导致我在这里提出问题的情况:

function className (){    
    var private_variable = 0;        
    function privateMethod(){
        // Some irrelevant code.
    };    
    this.privilegedMethod = function (){
        // Some relevant code to determine if private variable needs to be modified.
        private_variable+=val;    // Modifies private variable.
    };    
    this.init = function () {
        $(window).keydown(function (key) {
            if (key.which == 13) {
                privateMethod();    // Call to private method works fine.
                this.privilegedMethod();    // 'this' references Window object,
                                            // not this class method as expected.
            }
        });
    };  
};

我的问题是 - 是否有另一种方法可以调用 this.privilegedMethod() 引用它的类,而不是应用它的 Window 对象?

或者任何建议我可以如何重构我的代码以保持功能 - 全局监听关键事件,修改私有变量的方法可以在类外部访问,但私有变量本身不是。

附:在私有内部调用特权方法并没有改变任何东西。

【问题讨论】:

    标签: javascript jquery this privileged-functions


    【解决方案1】:
    this.init = function () {
        var that = this;
        $(window).keydown(function (key) {
            if (key.which == 13) {
                privateMethod();
                that.privilegedMethod();
            }
        });
    };  
    

    this.init = function () {
        $(window).keydown($.proxy(function (key) {
            if (key.which == 13) {
                privateMethod();
                this.privilegedMethod();
            }
        }, this));
    };  
    

    【讨论】:

    • 我认为“self”对于以这种方式使用的变量来说是一个更好的名称,因为它是一些其他语言使用的,而不是“this”,因此更具有同义性。
    • 使用 self 也可能出于同样的原因导致混淆,因为 JS 新手可能会认为这是一个实际的关键字。
    【解决方案2】:

    问题是keydown处理程序内部的作用域是窗口对象,所以“this”关键字指的是没有你方法的窗口。

    James 解决方案应该可以正常工作。

    【讨论】:

      【解决方案3】:
      function className (){    
          var private_variable = 0;        
          function privateMethod(){
              // Some irrelevant code.
          };    
          this.privilegedMethod = function (){
              // Some relevant code to determine if private variable needs to be modified.
              private_variable+=val;    // Modifies private variable.
          };    
      
          this.init = function () {
              var handle = $.proxy(this.privilegedMethod, this);
              $(window).keydown(function (key) {
                  if (key.which == 13) {
                      privateMethod();    
                      handle();                                                 
                  }
              });
          };  
      };
      

      http://api.jquery.com/jQuery.proxy/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-28
        相关资源
        最近更新 更多