Implementation of self-calling anonymous functions
- Method 1 (Note: Previous; Do not omit, to prevent the lack of previous statements; End)
;(function (win, $) {
//handle
})(window, jQuery);
- Method 2
!function (win, $) {
//handle
}(window, jQuery);
- Method Three
(function (win, $) {
//handle
}(window, jQuery));
Here is a simple plug-in case
Introduce your own jquery library and click li to print the contents in console (either of the three ways above)
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title></head>
<body>
<h4>Anonymous self-calling function wrapper plugin</h4>
<ul id="list">
<li class="item">aaaaaaaa</li>
<li class="item">bbbbbbbbb</li>
<li class="item">cccccccccccc</li>
<li class="item">dddddddddd</li>
</ul>
<script src="../js/jquery1.42.min.js"></script>
<script>
;(function (win, $) {
var plugin = function (item) {
this.item = $(item);
this.clickEvent();
};
plugin.prototype.clickEvent = function () {
this.item.click(function(){
console.log($(this).text());
});
};
plugin.init = function (itemLists) {
var _this = this;
itemLists.each(function (key, item) {
new _this(item);
});
};
win.MyTapPlugin = plugin;
})(window, jQuery);
</script>
<script>
MyTapPlugin.init($('#list .item'));
</script>
</body>
</html>
Cautions for encapsulating plug-ins
Internal instantiation must understand whether an object or an array is passed in.If it is an object, instantiate it directly with new this(selector); if it is an array, instantiate it with a loop for (){} or each().It is also important to mention that this points to an issue in the each loop, which can be achieved by referring to the above case.
The object passed in by jquery, the instantiated item is the dom node, requiring $(item) to restore jQuery as an object