Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add static method to built in class in JavaScript

I'd like to create a tryParse() static method for Date class. How can I do that?

Date.prototype.tryParse = function (value, result) {
    // ... Code ...
};

This adds an instance method, not a static class method. Any idea?

like image 752
Adam Szabo Avatar asked Jul 23 '26 02:07

Adam Szabo


1 Answers

First: you really, really shouldn't. To avoid collisions and incompatibilities, it's really much, to keep that sort of method in a namespace specific to your project:

var myUtils = {};
myUtils.tryParseDate = function(…) {…}

BUT! If you really, really, want to:

Date.tryParse = function(…) {…}
like image 127
David Wolever Avatar answered Jul 25 '26 17:07

David Wolever