Monday, April 11, 2011

Augmenting functions in JavaScript

This trick comes from Douglas Crockford’s JavaScript the good parts book (a must read); which, pour some syntactic sugar on our JavaScript code.

First we extend the global Function object via prototypal inheritance with a new method called "method". This method will allows us to skip the prototype call every time we need to extend an object. 

  Function.prototype.method = function (name, _function) {
        this.prototype[name] = _function;
        return this;
    };

And we are done.

Usage:
  <script language="JavaScript" type="text/JavaScript">


        function mainOperation() {
            this.main = 'main';
        }

        mainOperation.method('callMain', function () {
            alert('hi '+this.main);
        });

        window.onload = function () {
            var m = new mainOperation();
            m.callMain();
        };
     </script>


First we created a new object called "mainOperation()". Then, we augmented this object with the method "callMain" by using our new "method" property. Finally, to demonstrate what we just did we create on the window.onload a new instance of "mainOperation" and called the new "callMain" method.   

Output:




Recommended Reading:
JavaScript: The Good Parts

No comments:

Post a Comment