2013-01-18 28 views
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。 Obvisouly上面的方法是行不通的,你可以在这里看到:

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)所有的时间在每一个方法,但我很好奇,看看是否有解决这个问题的任何其他解决方案。随着方法数量的增长,随着时间的推移很难追踪这个属性。

回答

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进行始终如一的属性。

+0

哦,看起来不错,让我试试... – elclanrs

+0

工作完美!我必须在整个代码中更改'newFoo'的上下文,并添加相当多的'var self = this'来保持上下文正确,但它似乎工作正常。 – elclanrs

0

改变 '一个' 功能

a: function() { 
    var result = []; 
    // do something and push to result 
    if (this.prop){} // so something different with result 
    return newFoo(result); 
    }, 
0
function Foo(arr, prop) { 
    this.arr = arr; 
    this.isOn = prop || false; // if prop is undefined, set false 
} 

这应该弄清楚你的问题。

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

+0

我想你误解了这个问题。我意识到这一点,加上'undefined'是虚构的......我想要的是保持传递'prop'而不必将旧值传递到每个新实例,如果这是可能的/也许是一种不同的方法? – elclanrs