I was trying to extend the Javascript Date object. I've done it, but there's a strange behaviour i found. I added my own method 'lastYear' that returns the last year as a result.
I've tried to extend the Date object with 2 ways.
- Without arrow function
- With arrow function
However without arrow function, it works totally fine and it has access to the existing methods like 'getFullYear'.
Date.prototype.lastYear = function () {
console.log(this.getFullYear() - 1)
}
But when i changed the above code in the arrow function, it threw an error, that 'getFullYear is not a function'
Date.prototype.lastYear = () => {
console.log(this.getFullYear() - 1)
}
**Error**
*TypeError: this.getFullYear is not a function
at Date.lastYear (/home/runner/Javascript/index.js:6:20)
at /home/runner/Javascript/index.js:9:24
at Script.runInContext (vm.js:130:18)
at Object.<anonymous> (/run_dir/interp.js:209:20)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47*
Can someone explain me, what happened here..??