如果需要,链接函数并在链中保留变量

时间:2013-01-18 08:08:03

标签: javascript prototype chaining

我有一些像这样的代码:

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 ),但我很想知道这个问题是否还有其他解决办法。随着方法数量的增加,随着时间的推移很难跟踪这个属性。

3 个答案:

答案 0 :(得分: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来表示always-truthy属性。

答案 1 :(得分:0)

将'a'功能更改为

a: function() {
    var result = [];
    // do something and push to result
    if ( this.prop ){} // so something different with result
    return newFoo( result );
  },

答案 2 :(得分:0)

function Foo( arr, prop ) {
    this.arr = arr;
    this.isOn = prop || false; // if prop is undefined, set false
}

这应该解决你的问题。

如果您不添加prop参数,则isOn将设置undefined。这就是为什么你得到undefined作为输出。