简体   繁体   中英

how does no conflict work in jQuery plugin

// COLLAPSE PLUGIN DEFINITION
  // ==========================

  var old = $.fn.collapse

  $.fn.collapse = function (option) {
   ......
  }

  $.fn.collapse.Constructor = Collapse


  // COLLAPSE NO CONFLICT
  // ====================

  $.fn.collapse.noConflict = function () {
    $.fn.collapse = old
    return this
  }

This is the code from bootstrap 3 Collapse plugin. I am learning js by readying this plugin code.

I understand the syntax, but I have no idea how the no conflict works? Why this way can handle the conflict? what does "this" point to?

Thank you!

What this does is first assigns the original value of $.fn.collapse to a variable, old . That way it can keep a reference when overwriting.

In the $.fn.collapse.noConflict function, it puts back the original value of $.fn.collapse , from the variable old . return this allows you to set this collapse plugin to a different variable.

var collapsePlugin = $('*').collapse.noConflict();

jQuery.noConflict will reset the $ variable so it's no longer an alias of jQuery. Aside from just calling it once, there's not much else you really need to do. Though, you can create your own alias with the return value, if you'd like:

 var j = jQuery.noConflict();

 // Do something with jQuery
 j( "div p" ).hide();

 // Do something with another library's $()
 $( "content" ).style.display = "none";

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