2015-05-07 25 views
3

我在一個對象上有一系列的鏈接函數。例如:打破鏈接功能

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 

但我怎麼會擺脫這種讓ab執行,但從未達到c

+0

如果你寫'c()',它將被執行。你可以做一個事情是取代B'的'的返回值'{C:函數(){}}'但是這是令人厭惡的。 –

+0

@OmarElawady會引發錯誤 – Mark

+0

如果您啓動了它,則無法退出該功能。該函數在return語句或其主體結尾處結束。 –

回答

2

顯而易見的答案是「只是不要撥打c」,但我想這不是一個選擇出於某種原因。

這且不說,你可以破解它周圍的c之前從函數調用一個拋出一個錯誤,但我不會推薦它。例外是錯誤處理,而不是流量控制[*]。

var obj = {}; 
obj.a = function(){ 
    console.log('in a'); 
    return this; 
}; 


obj.b = function(){ 
    console.log('in b'); 
    if(shouldBreak) { 
     throw new Error('decided to break'); 
    } 

    return this; 
}; 

obj.c = function(){ 
    console.log('in c'); 
    return this; 
}; 

try { 
    obj.a().b().c(); 
} catch { 
    console.log('broke early') 
} 

[*] unless you're into Python

-1

位於a()b()類字段是由c()檢查。

0

只需添加你的方法以外的變量,說這就是所謂的標誌,默認爲真。

你不想經過短短設置標誌設置爲false待續任何方法。然後在返回之前測試標誌。

因此,像:

var flag = true 

function b() { 
    flag = false 
    return this 
} 

function c() { 
    return flag ? this : null 
} 
0

最簡單的方法是你打出來的任何函數調用的同樣的方式:拋出一個錯誤。

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();