未捕获的TypeError:this._isDateType不是Arrow函数内的函数&Quot;(&Q;) [英] "Uncaught TypeError: this._isDateType is not a function" within Arrow Function

查看:27
本文介绍了未捕获的TypeError:this._isDateType不是Arrow函数内的函数&Quot;(&Q;)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我每次都会收到找不到函数定义的类型错误。代码如下所示:

return BaseController.extend("ch.micarna.weightprotocol.controller.Calendar", {
  onInit: function () {
    console.log(this._isDateType(new Date()));
    let oHbox = this.byId("calendar-container");
    let oTodayDate = new Date();
    let oEndDate = this._getLastDayOfMonth(oTodayDate);
  },

  _getLastDayOfMonth: (oBegin) => {
    if (this._isDateType(oBegin)) {
      throw new TypeError("The given parameter is not type of date.");
    }
    return new Date(oBegin.getFullYear(), oBegin.getMonth() + 1, 0);
  },

  _isDateType: (oDate) => {
    return Object.prototype.toString.call(oDate) === "[object Date]";
  },

});

问题在于_isDateType函数在_getLastDayOfMonth函数内调用时找不到它。 我设置了断点:

如您所见,该函数未定义,我不知道原因。

onInit函数的开头,我调用了_isDateType函数:

console.log(this._isDateType(new Date()));

,并提供了预期的结果。

我做错了什么?

推荐答案

替换箭头函数

_getLastDayOfMonth: (oBegin) => {
  // this....
},

正常function expression

_getLastDayOfMonth: function(oBegin) {
  // this...
},

这样_getLastDayOfMonth可以自由访问Controller实例内的其他方法。

为什么它不能与箭头函数配合使用

  • 首先,重要的是要知道箭头函数在词法上绑定它们的上下文

    箭头函数表达式的语法比函数表达式短,没有自己的this[source]

    例如,不可能在箭头函数上调用.bind。它们在评估时从闭包中获取this

  • 由于this不是控制器的实例,而是调用BaseController.extend时的window对象,因此在箭头函数内部调用this._isDateType等同于window._isDateType

这篇关于未捕获的TypeError:this._isDateType不是Arrow函数内的函数&Quot;(&Q;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆