function getExperience(level, experience){
if(level == 'S'){
return 4*experience
}
if(level == 'A'){
return 3*experience
}
if(level == 'B'){
return 2*experience
}
return experience
}
// 改为策略模式 分成两个函数来写
const strategy = {
'S' : function(experience){
return 4*experience
},
'A' : function(experience){
return 3*experience
},
'B' : function(experience){
return 2*experience
}
}
// getExperience可以复用
function getExperience(strategy, level, experience){
return (level in strategy) ? strategy[level](experience) : experience
}
var s = getExperience(strategy, 'S', 100)
var a = getExperience(strategy, 'A', 100)
console.log(s, a) // 400 300
// 指令处理集合
var compileUtil = {
// v-text更新视图原理
text: function(node, vm, exp) {
this.bind(node, vm, exp, 'text');
},
// v-html更新视图原理
html: function(node, vm, exp) {
this.bind(node, vm, exp, 'html');
},
// v-class绑定原理
class: function(node, vm, exp) {
this.bind(node, vm, exp, 'class');
},
bind: function(node, vm, exp, dir) {
// 不同指令触发视图更新
var updaterFn = updater[dir + 'Updater'];
updaterFn && updaterFn(node, this._getVMVal(vm, exp));
new Watcher(vm, exp, function(value, oldValue) {
updaterFn && updaterFn(node, value, oldValue);
});
}
......
}
使用策略模式验证表单
// 我们写一个form表单
id="tip">
const strategies = {
// 非空
noEmpty: function(value, errMsg){
if(value === ''){
return errMsg
}
},
// 最小长度
minLength: function(value, length, errMsg){
if(!value || value.length < length){
return errMsg
}
},
// 最大长度
maxLength: function(value, length, errMsg){
if(value.length > length){
return errMsg
}
}
}
// 创建验证器
var Validator = function(strategies){
this.strategies = strategies
this.cache = [] // 存储校验规则
}
// 添加校验规则
Validator.prototype.add = function(dom, rules){
rules.forEach(item => {
this.cache.push(() => {
let value = dom.value
let arr = item.rule.split(':')
let name = arr.shift()
let params = [value, ...arr, item.errMsg]
// apply保证上下文一致
return this