https://segmentfault.com/a/11...
我放到了codepen
这篇文章中,对Validator.prototype.add方法中一处地方不理解
为什么要放到自执行函数中。
for(var i = 0, rule; rule = rules[i++];) {
(function(rule) {
var strategyAry = rule.strategy.split(':');
var errorMsg = rule.errorMsg;
self.cache.push(function() {
var strategy = strategyAry.shift();
strategyAry.unshift(dom.value);
strategyAry.push(errorMsg);
return strategies[strategy].apply(dom, strategyAry);
})
})(rule)
}
如果去掉外层的匿名函数就不行。 有什么区别吗?
for(var i = 0, rule; rule = rules[i++];) {
var strategyAry = rule.strategy.split(':');
var errorMsg = rule.errorMsg;
self.cache.push(function() {
var strategy = strategyAry.shift();
strategyAry.unshift(dom.value);
strategyAry.push(errorMsg);
return strategies[strategy].apply(dom, strategyAry);
})
}
可能是因为这里可能会有异步操作吧