有没有办法简化这样的链式调用?
if (obj && obj.prop && obj.prop.subProp1 && obj.prop.subProp1.subPropFunc) {
obj.prop.subProp1.subPropFunc();
}
我能想到的唯一替代方案是
try-catch
。还有其他想法吗?*我真的很烦写这些。在coffeescript中使用
?.
要容易得多。有没有办法简化这样的链式调用?
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?");
}