Function.attempt
尝试执行多个函数,返回第一个执行成功的函数的返回值,没有执行成功的,则返回null。
语法:
Function.attempt(fn[, fn, fn, fn, ...]);
参数:
- fn - (function) 任意数量要执行的函数。
返回值:
- (mixed) 成功执行的方法的返回值。
- (null)如果所有传递的方法执行失败,返回null。
举例:
var result = Function.attempt(
function(){
return some.made.up.object;
},
function(){
return jibberish.that.doesnt.exists;
},
function(){
return false;
});//返回 false
var failure, success;
Function.attempt(
function(){
some.made.up.object = 'something';
success = true;
},
function(){
failure = true;
});
if (success) alert('yey!');
注意: 等价于Mootools1.2中的$try。