Following code snippet in typescript does not work the way I mean. It should be self-explanatory:
declare interface Date {
toUrlString(): string;
}
Date.prototype.toUrlString = () => {
return this.toISOString().substring(0, 10);
};
document.write(
new Date().toUrlString()
// Error: Object [object Window] has no method 'toISOString'
);
Compiled code is:
var _this = this;
Date.prototype.toUrlString = function () {
return _this.toISOString().substring(0, 10);
};
document.write(new Date().toUrlString());
How can I fix this?
The
=>‘fat arrow’ notation invokes lexical scoping rules. Use a traditional function if you don’t want that: