JavaScript写作技巧,函数A中调用函数B, 怎样在函数B中写代码中断函数A的运行?
34 }
35 alert(arr.find(foo))
36
37 </script>
在第24行,如果程序已经找到第一个满足函数返回值为真的元素,那么就抛出一个自定义异常,终止 this.each()的
运行.. 注意第12行,只有确保函数抛出的是自定义异常才继续向上抛出异常,从而终止函数的运行.
在上面的代码中,我用的 try---catch方法完全是用来解决本贴所提出的问题的,并未进行任何其他错误处理.
在这方面,prototype.js ,通过定义两个自定义异常对象 $break 和 $continue ,既照顾到了异常处理,又解决了本贴
提出的问题. Enumerable 对象实现得很优雅, 大家不妨再去体会体会 prototype.js 中Enumerable的妙处.
我们看看prototype.js 是怎么做的,我还是贴出来把
prototype.js的代码片段摘取
var $break = new Object();
var $continue = new Object();
var Enumerable = {
each: function(iterator) {
var index = 0;
try {
this._each(function(value) {
try {
iterator(value, index++);
} catch (e) {
if (e != $continue) throw e;
}
});
} catch (e) {
if (e != $break) throw e;
}
},
all: function(iterator) {
var result = true;
this.each(function(value, index) {
result = result && !!(iterator || Prototype.K)(value, index);
if (!result) throw $break;
});
return result;
},
any: function(iterator) {
var result = true;
this.each(function(value, index) {
if (result = !!(iterator || Prototype.K)(value, index))
throw $break;
});
return result;
},
http://www.cnblogs.com/ashun/archive/2006/11/29/function_call_prototype_break_continue_gorush.html