码迷,mamicode.com
首页 > Web开发 > 详细

js 策略模式

时间:2018-01-08 18:31:10      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:适合   fine   pos   策略   var   typeof   定义   console   16px   

定义的一组算法(封装的功能或者模块,具有多种键的json对象被一个统一的方法管理)封装起来,使其相互之间可以替换。

适合表单验证

//策略
var strategy={
jump:function (who) {
console.log(who+‘ is jump‘);
},
run:function (who) {
console.log(who+‘ is run‘);
}
};
//统一处理方法
var useStrategy=(function () {
return{
on:function (arg1, arg2) {
strategy[arg1] && strategy[arg1](arg2);
},
add:function (param, fn) {
if(typeof strategy[param]===‘undefined‘){
strategy[param]=fn;
}else{
console.warn(‘这个方法已经存在‘);
}
}
}
})();
useStrategy.on(‘jump‘,‘james‘);
useStrategy.add(‘jump‘,function () {
console.log(‘1‘)
});
useStrategy.add(‘eat‘,function () {
console.log(‘eating‘)
});
useStrategy.on(‘eat‘)

js 策略模式

标签:适合   fine   pos   策略   var   typeof   定义   console   16px   

原文地址:https://www.cnblogs.com/redn/p/8118674.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!