最簡單的方法是你打出來的任何函數調用的同樣的方式:拋出一個錯誤。
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;
}
}
你想避免的一件事是using exceptions for flow control。
如果您需要致電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();
}
感覺就像醜陋的代碼(和它有點),但這種傳達在這些方法調用中引發的任何錯誤都是災難性的,顯示停止錯誤。如果你有一個複雜的操作,涉及多個方法調用一個物體或多個物體上,考慮封裝在一個「command」:
function DoSomethingCommand(obj) {
this.obj = obj;
}
DoSomethingCommand.prototype = {
constructor: DoSomethingCommand,
execute: function() {
this.obj.a().b();
if (someCondition) {
this.obj = this.obj.c();
}
}
};
從調用代碼的角度來看,它只是一個簡單的調用到開始真正複雜的過程:
var command = new DoSomethingCommand(obj);
command.execute();
如果你寫'c()',它將被執行。你可以做一個事情是取代B'的'的返回值'{C:函數(){}}'但是這是令人厭惡的。 –
@OmarElawady會引發錯誤 – Mark
如果您啓動了它,則無法退出該功能。該函數在return語句或其主體結尾處結束。 –