我在一个对象上有一系列链式函数。例如:
var obj = {};
obj.a = function(){
console.log('in a');
return this;
};
obj.b = function(){
console.log('in b');
return this;
};
obj.c = function(){
console.log('in c');
return this;
};
obj.a().b().c();显然,当我查看控制台时,结果是:
in a
in b
in c但是,我如何才能摆脱这种情况,让a和b执行,但却永远无法到达c?
发布于 2015-05-07 15:51:34
只需在方法之外添加一个变量,例如它被称为标志,默认为true。
在将标志设置为false之后,您不想继续的任何方法。然后在返回此标记之前进行测试。
所以,就像:
var flag = true
function b() {
flag = false
return this
}
function c() {
return flag ? this : null
}发布于 2015-05-07 17:20:32
最简单的方法是,您可以从任何函数调用中分离出来:抛出一个错误。
var obj = {
someCondition: false,
a: function() {
return this;
},
b: function() {
if (!this.someCondition) {
var error = new Error("A message");
error.name = "SomeConditionError";
throw error;
}
return this;
},
c: function() {
return this;
}
};然后调用方法并处理错误。
try {
obj
.a()
.b() // throws a "SomeConditionError" here
.c();
}
catch (error) {
if (error.name == "SomeConditionError") {
// gracefully handle "SomeConditionError"
}
else {
// rethrow errors you don't know how to handle gracefully
throw error;
}
}您想要避免的一件事是使用异常进行流控制。
如果需要调用obj.a()然后调用obj.b(),然后有条件地调用obj.c(),则调用代码需要处理这一点:
obj.a().b();
if (someCondition) {
// Assign to "obj" just in case obj.c() returns a different object
obj = obj.c();
}它感觉像更丑陋的代码(而且有点),但这表明在这些方法调用中抛出的任何错误都是灾难性的、停止显示的错误。如果您有一个复杂的操作,涉及对一个或多个对象的多个方法调用,请考虑将其封装到一个“命令”中:
function DoSomethingCommand(obj) {
this.obj = obj;
}
DoSomethingCommand.prototype = {
constructor: DoSomethingCommand,
execute: function() {
this.obj.a().b();
if (someCondition) {
this.obj = this.obj.c();
}
}
};从调用代码的角度来看,这只是对execute()的简单调用,以启动真正复杂的过程:
var command = new DoSomethingCommand(obj);
command.execute();发布于 2015-05-07 15:09:35
在a()或b()中设置由c()检查的类字段。
https://stackoverflow.com/questions/30104928
复制相似问题