I've got every time a type error that a function definition could not be found. The code looks as follow:
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]";
},
});
The problem is the _isDateType
function that could not be found when it is called inside the _getLastDayOfMonth
function.
I set the break point:
and as you can see, the function is undefined and I do not know why.
At the beginning of the onInit
function, I called the _isDateType
function:
console.log(this._isDateType(new Date()));
and it supply the result as expected.
What am I doing wrong?
Replace the arrow syntax ...
_getLastDayOfMonth: (oBegin) => {
... with a normal function expression:
_getLastDayOfMonth: function(oBegin) { // or _getLastDayOfMonth(oBegin) {
// this === Controller instance
}
By this, _getLastDayOfMonth
can freely access other methods within the Controller instance.
Arrow functions do not create their own this
, which is why this
usually refers to the context from the arrow function's lexical scope. Therefore, arrow functions, in general, should not be used as methods.
Arrow functions don't have their own bindings to
this
,arguments
, orsuper
, and should not be used as methods. [source]
In the above case, this
was referring to the window
object when BaseController.extend
was called. Calling this._isDateType
inside the arrow function was equivalent to window._isDateType
.