There are many forms of S plug-in, here I share a familiar ES5 syntax, first preview, then explain
; (function(global) { "use strict"; var MyPlugin = function(options) { }; MyPlugin.prototype = { init: function() { } }; if (typeof module ! == 'undefined' && module.exports) module.exports = MyPlugin; if (typeof define === 'function') define(function() { return MyPlugin; }); global.MyPlugin = MyPlugin; })(this);Copy the code
This is used to create a class. Although ES5 does not have a real class, it can only be simulated by function, which we will call a class for now. ES6 has the class keyword, which we won’t go into detail here. The above code compatible with CommonJs/AMD/CMD specifications, more general. Notes:
/ /; //(function(){})(); //(function(){})(); // Usually a plug-in exposes only one variable to the global for other programs to call // there are other ways to write it, operator + function body + parentheses // example:! function(){}(); +function(){}(); -function(){}(); // void function(){}(); Anything that operates on the return value of a function; (function(global) {// use strict; Var MyPlugin = function(options) {}; Myplugin. prototype = {init: function() {}}; // Compatible with CommonJs specification if (Typeof Module! == 'undefined' && module.exports) module.exports = MyPlugin; If (typeof define === 'function') define(function() {return MyPlugin; }); Global.myplugin = MyPlugin; global.myplugin = MyPlugin; // This, in the browser environment refers to window, in the nodejs environment refers to global // This is used instead of window/global, which is compatible with the browser and server side // This is passed into the function body, making the global variable local. Shorten the time a function accesses a global variable})(this);Copy the code
Next, develop a plugin that can change the div background color
- modify_div_bg.js
; (function(global) { "use strict"; var M = function(el) { this.el = typeof el === "string" ? document.querySelector(el) : el; }; M.prototype = { setBg: function(bg) { this.el.style.background = bg; }}; if (typeof module ! == 'undefined' && module.exports) module.exports = M; if (typeof define === 'function') define(function() { return M; }); global.ModifyDivBg = M; })(this);Copy the code
- index.html
<! DOCTYPE HTML > < HTML lang=" zh-cn "> <head> <meta charset=" utF-8 "> <title> How to write js plugin </title> <script SRC ="./modify_div_bg.js"></script> </head> <body> <div id="div"> How to write a JS plugin </div> <script> var mObj = new ModifyDivBg("#div"); mObj.setBg("#f00"); </script> </body> </html>Copy the code
Put the modify_div_bg.js and index.html code in the same directory and open the index.html in Chrome to see the effect. Open the debug Console (Windows F12, Mac Option + Command + I) and type mObj. SetBg (“#ff0”). Press Enter to change the div background color.