를 필요한 경우 체인의 변수를 유지 :체인 연결 기능이 같은 일부 코드가
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)
}
};
내가 체인의 이전 요소가 prop
가있는 경우 true
을 통과 유지하려는합니다. 난 그냥 모든 방법에 newFoo(result, this.prop)
모든 시간을 반환 할 수 알고
var nf = newFoo;
console.log(nf([1,2,3]).b().isOn); //=> true
console.log(nf([1,2,3]).b().a().isOn); //=> undefined
을하지만, 나는이 문제에 다른 해결책이 있는지 궁금했다 : Obvisouly 당신이 여기에서 볼 수 있듯이 위의 방법이 작동하지 않습니다. 메소드가 숫자가 커지면 시간이 지남에 따라이 속성을 추적하기가 어려울 것입니다.
오, 멋지다, 내가 그것을 시도하자. ... – elclanrs
완벽하게 일했다! 코드 전체에서 'newFoo'의 컨텍스트를 변경하고 컨텍스트를 올바르게 유지하기 위해 'var self = this'를 추가해야했지만 제대로 작동하는 것 같습니다. – elclanrs