vsahu vsahu - 3 months ago 17
Ajax Question

Does calling jQuery's ajaxSetup with no parameters have any side effects?

I've read the answers here and here that describe how to read the value of jQuery ajax settings. My question, however, is this: if I have previously invoked the ajaxSetup function with settings, like

$.ajaxSetup({cache: true})
, and then I invoke
$.ajaxSetup()
(with no arguments), are there any side effects to this invocation? Or more bluntly, does calling
$.ajaxSetup()
with no arguments do anything
other than return a plain object that contains the settings for ajax?

The answers I've referenced above both call ajaxSetup in this way in order to read the value of a setting, and I have been unable to find any official answer on the jQuery docs that indicate what calling ajaxSetup with no parameters does, probably because its use is so heavily discouraged. In my browser, I ran a simple test by loading jQuery, running
$.ajaxSetup({async: false});
followed by
$.ajaxSetup();
and found that the value of async was still unchanged (the default value is true, and so if calling
$.ajaxSetup()
reset the settings to default values, then the value of async should have been changed), but this probably isn't strong enough evidence to conclude that side effects do not occur when the function is invoked in this way.

Answer

Does calling $.ajaxSetup() with no arguments do anything other than return a plain object that contains the settings for ajax?

No.

Example

// set a new custom url
$.ajaxSetup({
  url: 'CHANGED'
});

// call it again with no params
$.ajaxSetup();

// the url is still the custom url
console.log('url: ' + $.ajaxSetup().url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Why?

If we look at the code for ajaxSetup, we see that, when called with a single parameter, it returns the call:

ajaxExtend( jQuery.ajaxSettings, target );

where target is the single argument you passed into ajaxSetup().

Now, inside ajaxExtend, we can see that it tries to iterate over that same argument with a for in loop.

Relevant code:

function ajaxExtend( target, src ) {

    for (var key in src) {
      // here is where target, which in this case is jQuery.ajaxSettings, gets overriden
    }

    return target;
}

Since you don't pass anything, basically you are doing

function ajaxExtend( target, src ) {

    for (var key in undefined) {
      // this is never reached
    }

    return target;
}

which never enters the for in loop and returns the current value of jQuery.ajaxSettings.