js self-calling anonymous functions and internal instantiation wrapper plug-in

Implementation of self-calling anonymous functions

  • Method 1 (Note: Previous; Do not omit, to prevent the lack of previous statements; End)
;(function (win, $) {
})(window, jQuery);
  • Method 2
!function (win, $) {
}(window, jQuery);
  • Method Three
(function (win, $) {
}(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>
<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>
<script src="../js/jquery1.42.min.js"></script>
    ;(function (win, $) {
        var plugin = function (item) {
            this.item = $(item);
        plugin.prototype.clickEvent = function () {
        plugin.init = function (itemLists) {
            var _this = this;
            itemLists.each(function (key, item) {
                new _this(item);
        win.MyTapPlugin = plugin;
    })(window, jQuery);
    MyTapPlugin.init($('#list .item'));

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

Tags: JQuery

Posted on Wed, 13 May 2020 13:46:31 -0400 by texhead