0

次のようなコードがあります。

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 )すべてのメソッドで常に戻ることができることはわかっていますが、この問題に対する他の解決策があるかどうかを知りたいと思っていました. メソッドの数が増えると、このプロパティを追跡するのが難しくなります。

4

3 に答える 3

2

メソッドの数が増えるにつれて、このプロパティを長期にわたって追跡することは困難になります。

newFoo上書きしないプロパティを自動的に追跡する機能を備えた追加のメソッドを作成するだけで済みます。

function Foo( arr, prop ) {
  this.arr = arr;
  this.isOn = prop;
}

Foo.prototype = {

  clone: function newFoo( arr, prop ) {
    return new Foo(
      arguments.length >= 1 ? arr : this.arr,
      arguments.length >= 2 ? prop : this.isOn
    );
  },

  a: function() {
    var result = [];
    // do something and push to result
    if ( this.prop ) // do something different with result
    return this.clone( 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 this.clone( result, true )
  }

};

arguments.lengthここでは、パラメーターが渡されたかどうかを確認するために使用しました。常に真のプロパティに対してテストしたり、undefined単純なプロパティを使用したりすることもできます。arr || this.arr

于 2013-01-18T08:24:34.920 に答える
0

「a」関数をに変更

a: function() {
    var result = [];
    // do something and push to result
    if ( this.prop ){} // so something different with result
    return newFoo( result );
  },
于 2013-01-18T08:10:24.793 に答える
0
function Foo( arr, prop ) {
    this.arr = arr;
    this.isOn = prop || false; // if prop is undefined, set false
}

これで問題が解決するはずです。

prop引数を追加しない場合は、 isOnset になりますundefined。そのためundefined、出力として取得されます。

于 2013-01-18T08:11:44.133 に答える