Javascript – Is the capability to overwrite functions in JavaScript strength or weakness

javascript

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?

Best Answer

I think it really depends on who you ask. Javascript is by no means a perfect language, but just like abstraction of private variables, this may be a good or bad thing depending on the situtation.

If you're using a library and want to overwrite a function, then it's a good thing, if you're the author of a library or function, and someone uses your code in a way you do not intend, then it is not.

Related Topic