JS 制作插件
最后更新于:2022-04-02 03:24:41
[TOC]
## 方式一
打印节点
```
(function(win){
'use strict';
var document = win.document; //非必须
function ready(selector, fn){
check(selector,fn);
}
function check(selector,fn){
var dom =document.querySelector(selector)
fn(dom);
}
// 对外暴露ready
win.getDom = ready;
})(this);
// usage
getDom('h1', function(element){
console.log(element);
});
```
## 方式二
```
/**
*
* @type {{minus(*): void, regiset(*): void, setValue(*): void, currentValue: number, plus(*): void}}
*
*/
const Calc = {
currentValue: 0,
setValue(newValue) {
this.currentValue = newValue;
console.log(this.currentValue);
},
core: {
'plus': (currentValue, addend) => currentValue + addend,
'minus': (currentValue, addend) => currentValue - addend,
},
plugins: {},
press(method, newVal) {
const func = this.core[method] || this.plugins[method];
this.setValue(func(this.currentValue, newVal));
},
register(plugin) {
const {name, exec} = plugin
this.plugins[name] = exec
}
}
const squaredPlugin = {
name: "squared",
exec: function (currentValue) {
return currentValue*currentValue
}
}
Calc.register(squaredPlugin)
// 使用计算器
Calc.setValue(3); // => 3
Calc.press('plus', 2); // => 5
Calc.press('squared'); // => 25
Calc.press('squared'); // => 625
```
';