代码之家  ›  专栏  ›  技术社区  ›  Jessica

Public方法在调用[duplicate]时返回“not a function”错误

  •  0
  • Jessica  · 技术社区  · 6 年前

    我想打电话给 this 在我的课堂上。当我这样做的时候,我会得到一个错误,说:

    未捕获类型错误:this.logMe不是函数

    我试着搬走了 但它仍然有一个错误。这是我的密码:

    function Logger() {
        this.logMe = function() {
        console.log('Log a Message');
      };
    
      window.addEventListener('click', function() {
            this.logMe();
      });
    }
    
    var hello = new Logger();
    

    4 回复  |  直到 6 年前
        1
  •  1
  •   D-Shih    6 年前

    你的 this Logger

    function() {
        // this is about this anonymous method instead of Logger
        this.logMe();
    }
    

    window.addEventListener('click', this.logMe); 让你期待。

    function Logger() {
        this.logMe = function() {
        console.log('Log a Message');
      };
    
      window.addEventListener('click', this.logMe);
    }
    
    var hello = new Logger();
        2
  •  0
  •   Martin Zeitler    6 年前

    var Logger = {
      log: function(msg) {
          if(typeof(msg) != 'undefined') {
              console.log(msg);
          }
      }
    };
    
    window.addEventListener('click', function() {
       Logger.log('Log a Message');
    });
        3
  •  -1
  •   ghuntheur    6 年前

    function Logger() {
        this.logMe = function() {
        console.log('Log a Message');
      };
    
      window.addEventListener('click', () => this.logMe(), false);
    }
    
    var hello = new Logger();

    看看这个: https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4

        4
  •  -2
  •   Raj    6 年前

    它会像预期的那样工作。

    function Logger() {
      logMe = function() {
        console.log('Log a Message');
      };
    
      window.addEventListener('click', function() {
            logMe();
      });
    }
    
    var hello = new Logger();