JQuery extension extended simple implementation principle of extend, jqueryextend
I believe that every front-end partner is familiar with jQuery. One of its greatest charms is that there are a large number of plug-ins to help us implement various functions more easily.
A few nights ago, when I had nothing to do, I wrote a simple jQuery plug-in by myself. The function was very simple, but it only highlighted the selected elements. However, some of the ideas are worth learning,You can click here to view the code.
This article does not talk about how to write the jQuery plug-in. Let's talk about how to implement jQuery's plug-in extension function, and how to mount the plug-in we wrote to jQuery through extend. (Daniel can turn right when going out ......)
We can simulate the creation of a mini jQuery.
var $ = {};
Okay, that's simple ......
Next we will mount an extend Method on this object to allow developers to add functions and methods for this object.
Var $ = {extend: function (ob) {/** no matter what is written in it temporarily **/}}
Now, we have added an extend Method to the $ object, which can be called externally through the $. extend (obj) method.
Suppose we want to add a method to $, that is, to add a plug-in, we only need:
$.extend({ myFunction:function(obj){ //do something.... } })
Now you only need $. myFunction (obj); To implement what you need to do in the method.
The key to the problem is that we mount the method on $. extend. Why can we call it directly with $? Here we will look at how to process the passed obj in extend.
var $ = { extend:function(obj){ for(var key in obj){ this.__proto__[key]=obj[key]; } }}
It turns out that extend traverses the passed obj and mounts it to _ proto _ of $. In this way, $ can call methods on the prototype at any time.
Of course, in fact, jQuery's extend implementation is much more complicated than this. Here we only introduce the basic idea of the underlying implementation of jQuery plug-in, and mount public methods to the object prototype.
For details about plug-in writing, refer to the link at the beginning of the article. I have commented on every detail of the plug-in writing and learned from each other!
The above is the simple implementation principle of the jQuery extension extend provided by the mini-editor. I hope you can provide more support ~