有没有办法缩短这种连锁电话?
if (obj && obj.prop && obj.prop.subProp1 && obj.prop.subProp1.subPropFunc) {
obj.prop.subProp1.subPropFunc();
}
我能想象的唯一选择是try-catch
. 还有其他想法吗?
*我真的厌倦了写这些。在咖啡脚本中使用?.
.
有没有办法缩短这种连锁电话?
if (obj && obj.prop && obj.prop.subProp1 && obj.prop.subProp1.subPropFunc) {
obj.prop.subProp1.subPropFunc();
}
我能想象的唯一选择是try-catch
. 还有其他想法吗?
*我真的厌倦了写这些。在咖啡脚本中使用?.
.
考虑到您的示例代码,这应该可以工作(没有测试“所有案例”,只是您的示例的副本):
function propsExist(obj) {
if (!obj) return false;
for (var i = 1; i < arguments.length; i++) {
if (!obj[arguments[i]]) return false;
obj = obj[arguments[i]];
}
return true;
}
if (propsExist(obj, "prop", "subProp1", "subPropFunc")) {
obj.prop.subProp1.subPropFunc();
}
该方法propsExist()
采用可变数量的参数,其中第一个是您要检查属性/函数的原始对象。它将遍历您发送给它的属性列表并按顺序检查它们。如果一个不存在,它将返回false
。如果它通过整个循环,则验证成功!
如果您总是想在验证时调用子属性的函数,您也可以只更改propsExist
函数以调用它而不是返回 true (然后将函数重命名为callIfValid(obj, ...)
与上一篇文章相同的想法,只是一个不同的解决方案。
function checkChain(variablePath,startingPoint){
var check = startingPoint || window,
parts = variablePath.split("."),
i;
for (i=0;i<parts.length;i++) {
check = check[parts[i]];
if (!check) {
return null;
}
}
return check;
}
var foo = { bar : { cat : { says : function(x){ alert(x); } } } };
var test1 = checkChain("foo.bar.cat.says");
if (test1) {
test1("meow");
}
var test2 = checkChain("foo.bar.cat.bark");
if (test2) {
test2("burp");
}
var test3 = checkChain("cat.says",foo.bar);
if (test3) {
test3("huh?");
}