Simple implementation principle of jQuery plug in extension extend

  • 2021-06-29 10:17:50
  • OfStack

Believe that each front-end buddy is familiar with jQuery, its biggest charm is that there are a large number of plug-ins to help us achieve various functions more easily.

The last few nights, when I was idle, I wrote a simple jQuery plug-in by myself. The function was simple, just to highlight the selected elements, but some of the ideas are worth learning. You can stamp here to see the code.

This article does not talk about how to write jQuery plug-ins, we talk about how to implement the plug-in extension function of jQuery, how extend can implement the plug-in we write to mount on jQuery. (Daniel can go out and turn right...

We can simulate the creation of a mini jQuery.

var $ = {};

Okay, it's that simple...

Next, we'll mount an extend method on this object that allows developers to add functions and methods to this object.

var $ = {
      /** Whatever is written in it for the moment **/

Now we've added an extend method to the $object that can be called externally through the $.extend (obj) method.

Suppose now that we want to add a method to $by adding a plug-in, we only need:

     //do something....   

All you need now is $.myFunction (obj);You can accomplish what you want to do within the method.

The key to the question is, we are mounting the method on $.extend. Why can we call it directly with $?Here's how the incoming obj is handled inside extend.

var $ = {
    for(var key in obj){

Originally, extend traversed the incoming obj and hung it to u of $proto_uYes, $can call the method on the prototype at any time.

Of course, the extend implementation of jQuery is actually much more complex than this one. This is just an introduction to the basic idea of the underlying implementation of the jQuery plug-in, which mounts common methods onto the prototype of the object.

Specific plug-in writing can see the link at the beginning of the article, I have commented on every detail of plug-in writing, everyone can learn from each other!

Related articles: