前端插件设计
最编程
2024-03-10 18:31:11
...
前言
从简单的例子开始:
function pluginA(App) {
App.protoType.a = 1;
}
function pluginB(App) {
App.protoType.b = 1;
}
class App { }
//对App原型进行增强
pluginA(App);
pluginB(App);
这种写法,从语义上看,plugin是主动施与者,为了统一对外接口,较多的写法为:
class App {
use(plugins) {
let type = Object.protoType.toString.call(plugins);
if(type === '[object Function]') {
plugins.call(null, this);
}else if(type === '[object Array]') {
plugins.forEach(plugin => {
pulgin.call(null, this);
});
}
}
}
//用法一
App.use(pluginA);
App.use(pluginB);
//用法二
App.use([pluginA, pluginB]);
由使用者提供接口,语义上更友好。App:"我需要pluginA"。pluginA便为之所用。是不是有些IOC的意思?