Learn Modern Unobtrusive JavaScript

106 172
The next step beyond using the built-in objects which JavaScript provides is to extend the functionality of those built-in objects to provide the additional processing that your scripts require that the objects don't provide.

JavaScript doesn't require that we just accept what we are given with the built-in objects and leave us to write our own code to handle the functionality that the built-in objects left out.


We don't even need to create our own objects based on the built-in ones in order to extend the functionality as we would with most other languages because JavaScript allows us to add our own methods to the existing built-in objects directly. What this means is that if one or more of the built-in objects doesn't supply us with all the methods we need then we can add our own methods directly into that object (and properties too if we really need them) and then access our additions as if they were a part of the original object.

I have written quite a few methods to extend some of the built-in objects and so rather than try to describe how to write one, I will just provide you with links to the ones that I have already written. You are welcome to use any of those with your JavaScript and also to use them as examples in order to see how to create your own.

Here are some methods you can add to all your dates:



    Of course the date object isn't the only one you can extend by adding your own methods. Here is the code you'd need to add a trim method th Strings that allows you to easily remove any leading and trailing whitespace.

    String.prototype.trim = function() {var re = /^\s*(.*?)\s*$/;return this.replace(re,"$1");}

    More of This Tutorial

    Source...

    Leave A Reply

    Your email address will not be published.