我有一些像这样的代码保持可变链:链接功能,如果需要
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)
所有的时间在每一个方法,但我很好奇,看看是否有解决这个问题的任何其他解决方案。随着方法数量的增长,随着时间的推移很难追踪这个属性。
哦,看起来不错,让我试试... – elclanrs
工作完美!我必须在整个代码中更改'newFoo'的上下文,并添加相当多的'var self = this'来保持上下文正确,但它似乎工作正常。 – elclanrs