Is the capability to overwrite functions in JavaScript strength or weakness?

Posted by S.N on Programmers See other posts from Programmers or by S.N
Published on 2011-11-10T22:29:08Z Indexed on 2011/11/12 2:12 UTC
Read the original article Hit count: 185

Filed under:

I recently came across the following code (from liferay.js) when I was working with Liferay:

....
if (!Liferay._ajaxOld) {
    Liferay._ajaxOld = jQuery.ajax;
}

if (Liferay._ajaxOld) {
    jQuery.ajax = function(options) {
        if (Liferay.Util) {
            options.url = Liferay.Util.getURLWithSessionId(options.url);
        }
        return Liferay._ajaxOld(options);
    };
}
....

As you can see, the code above overwrites the function "jQuery.ajax" to modify "options.url". One may say this is a strength of the language since we can easily overwrite and customize existing functions.

However, I would imagine this capability can easily lead to a problem. For instance, my code can overwrite the same function "jQuery.ajax" to modify "options.url" differently from the code above. As a result, any code that expect the behavior defined by "liferay.js" may no longer function as expected.

I see this as a weakness of the language as it does not provide proper encapsulation. What are the consensus about this feature/capability of the language in the field?

© Programmers or respective owner

Related posts about JavaScript