Home > Article > Web Front-end > A brief discussion on the implementation principle of jQuery plug-in extension extend
I believe that every front-end friend is familiar with jQuery. One of its biggest charms is that it has a large number of plug-ins to help us achieve various functions more easily. Function.
A few nights ago, when I had nothing to do, I wrote a simple jQuery plug-in by myself. The function is very simple, it just highlights the selected elements, but some of the ideas are still worth learning. Yes, You can click here to view the code.
This article will not talk about how to write jQuery plug-ins. Let’s talk about how to implement jQuery’s plug-in extension function. How extend implements mounting the plug-ins we wrote to jQuery. (Daniu can go out and turn right...)
We can simulate creating a mini jQuery.
var $ = {};
Okay, it’s that simple...
Next we need to mount an extend method on this object to allow Developers add functions and methods to my object.
var $ = { extend:function(ob){ /**暂时不管里面写什么**/ } }
Now, we have added an extend method to the $ object, which can be called externally through the $.extend(obj) method.
Suppose now we want to add a method to $, that is, add a plug-in, we only need:
$.extend({ myFunction:function(obj){ //do something.... } })
Now we only need $.myFunction(obj); to achieve it What needs to be done within the method.
Here comes the crux of the problem. We clearly mount the method on $.extend. Why can we call it directly with $? Here we need to see how extend handles the incoming obj internally.
var $ = { extend:function(obj){ for(var key in obj){ this.proto[key]=obj[key]; } } }
It turns out that extend traverses the incoming obj and then hangs it on the proto of $. In this way, $ can call methods on the prototype at any time.
Of course, the actual implementation of jQuery's extend is much more complicated than this. Here we only introduce the basic idea of the underlying implementation of the jQuery plug-in, which mounts public methods to the prototype of the object.
For specific plug-in writing, you can check out the link at the beginning of the article. I have annotated every detail of plug-in writing. Everyone can learn from each other!
The above is the detailed content of A brief discussion on the implementation principle of jQuery plug-in extension extend. For more information, please follow other related articles on the PHP Chinese website!