I don't mean what it is I mean it

The following piece of code in typescript doesn't work the way I do. This should be self-evident:

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:

var _this = this;
Date.prototype.toUrlString = function () {
    return _this.toISOString().substring(0, 10);
};
document.write(new Date().toUrlString());

      

How can I fix this?

+3


source to share


1 answer


The designation =>

"fat arrow" invokes the lexical rules for defining the area. Use the traditional function if you don't want it:



Date.prototype.toUrlString = function() {
    return this.toISOString().substring(0, 10);
};

      

+5


source







All Articles