3

私はチェス盤のようなオブジェクトの配列を持っています。それらのそれぞれには、topオブジェクトの隣人を返す関数があります。downleftright

data.field(3,3).left() //returns field(2,3);

私はそれを連鎖させることができます

data.field(3,3).left().left().top().right().down().getName();

しかし、次のような負のコードを持つオブジェクトはありません

data.field(-1,0)

指定されたコードがオブジェクト配列よりも負または大きい場合は、簡単に検出できます。false または空のオブジェクトを返すことができますが、何も返されず、チェーンが続行されるとエラーが発生します

Uncaught TypeError: Object #<error> has no method 'down'

これは問題ですが、jsの実行を停止するエラーを取得せずに、返すオブジェクトがないときに、このエラーを回避し、長いチェーンを停止するにはどうすればよいですか?

まあ言ってみれば:

data.left().left()/*here there is nothing to return*/.right().right().getName(); //should return false
4

2 に答える 2

2

無効な位置に対して null を返す代わりに、方向関数をオーバーライドして "invalid location" を返す getName 関数で null オブジェクトを返すカスタム "null オブジェクト" を返すか、これらの関数が呼び出されたときに例外をスローします。

nullObject = {

    this.left = function(){return this;}
    this.right =  function(){return this;}
    //etc
    this.getName = function(){"Invalid Location"}

}

例外処理は次のようになります

try{
  piece.left().right().down().getName()
}
catch(exc){
  //handle exception
}

ちなみに、ここでは基本的にモナドを作成しています。null オブジェクトを受け取ったときに計算を停止するように設定した場合は、多分モナドの例です。ただし、これは、ここでの実際的な懸念よりも理論的なレベルを少し上回っています。

于 2013-03-04T18:56:09.787 に答える
0

try/catch structure allows you to stop execution in case there is nothing returned. However, if you don't want to use try/catch, each method must be able to return an object which owns the same methods which return the object itself. In this case the chain will be entirely executed :

right: function () {
    var nextItem;
    // get next item to the right here
    return nextItem || {
        up: function () { return this; },
        right: function () { return this; },
        down: function () { return this; },
        left: function () { return this; }
    };
}
于 2013-03-05T08:59:22.267 に答える