第156天 用原生JS封装插件的方式有哪些?
一般的插件封装
;(function (global) {
"use strict";
function MyPlugin(el, options) {
//some cod
};
MyPlugin.prototype = {
//定义方法
show: function () {
//some code
}
};
if (typeof module !== 'undefined' && module.exports) { //兼容CommonJs规范
module.exports = MyPlugin;
} else if (typeof define === 'function') { //兼容AMD/CMD规范
define(function () {
return MyPlugin
})
} else { //注册全局变量,兼容直接使用script标签引入插件
global.MyPlugin = MyPlugin;
}
})(this);
还有像 jquery 那种 var $ = function() { return $.fn.init }; $.fn = {}; $.fn.init = function(){} 这种的;
或者 Object.defineProperty(String.prototype, 'red', { get: function(){ return this + 'red' } }) 这种的。
不只有 fn() 或 new func() 这样的插件,也有 fn.func() 和 fn.func 这样的插件的存在。
Most helpful comment
一般的插件封装