次のようなコードがあります。
function Foo( arr, prop ) {
this.arr = arr;
this.isOn = prop;
}
function newFoo( arr, prop ) {
return new Foo( arr, prop );
}
Foo.prototype = {
a: function() {
var result = [];
// do something and push to result
if ( this.prop ) // do something different with result
return newFoo( result );
},
// This is the method that determines if prop = true in the chain
b: function() {
result = [];
// do something and push to result
// this time 'prop' must be 'true'
return newFoo( result, true )
}
};
true
チェーンの前の要素に がある場合は、パスし続けたいですprop
。ここでわかるように、明らかに上記のアプローチは機能しません。
var nf = newFoo;
console.log( nf( [1,2,3] ).b().isOn ); //=> true
console.log( nf( [1,2,3] ).b().a().isOn ); //=> undefined
newFoo( result, this.prop )
すべてのメソッドで常に戻ることができることはわかっていますが、この問題に対する他の解決策があるかどうかを知りたいと思っていました. メソッドの数が増えると、このプロパティを追跡するのが難しくなります。