简体   繁体   中英

My $.extend does not seem to work when inside a function in javascript

I have the following code:

File 1:
$(document).ready(function () {
   addDataTableExts();
}

File 2:
function addDataTableExts() {
   $.extend($.fn.dataTableExt.oStdClasses, {
        sWrapper: 'no-margin last-child'
   }
}

This seems to work okay. I now tried to replace this with the following:

File 2:
(function () {

    $.extend($.fn.dataTableExt.oStdClasses, {
        sWrapper: 'no-margin last-child'
    }
}

This doesn't work.

Is there some reason why it only seems to work if I do this the first way? I thought that by changing the first line of File 2 then it would cause the code to get executed without me calling it.

You changed the code from running in the ready event to running immediately. It seems that you are loading your datatable plugin after loading file 2, so the plugin doesn't exist yet when you try to use it.

If you put it back in the ready event, it should work:

File 2:
$(document).ready(function () {

  $.extend($.fn.dataTableExt.oStdClasses, {
    sWrapper: 'no-margin last-child'
  }

});

Note: Events in jQuery are not exclusive, so you can have several ready event handlers in the same page without problems.

"I thought that by changing the first line of File 2 then it would cause the code to get executed without me calling it."

If you actually changed only the first line as shown then you've created a syntax error - you've added an opening ( without a closing ) . But simply adding the closing ) won't cause the now anonymous function expression to be executed. If you want the code to get executed without being called from File 1 you need to add extra parentheses () on the end to actually invoke the function.

Also you had a missing closing ) after the } at the end of $.extend(... , though that was also a problem in the first version of your code (and also a problem with the document ready handler in File 1).

(function () {
    $.extend($.fn.dataTableExt.oStdClasses, {
        sWrapper: 'no-margin last-child'
    });    // <-- add missing ); here
})();      // <-- add missing )(); here

But you don't need the containing function at all unless it also wraps other code that you don't show, because that $.extend() statement on its on doesn't have any deleterious effect on the global scope.

Finally, if you do need to run that $.extend() after the page is ready but don't want to have a dependency between your two files you can add a document ready handler directly in File 2. Multiple document ready handlers will all be executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM