2013-01-18 2 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) 
    } 

}; 

내가 체인의 이전 요소가 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 당신이 여기에서 볼 수 있듯이 위의 방법이 작동하지 않습니다. 메소드가 숫자가 커지면 시간이 지남에 따라이 속성을 추적하기가 어려울 것입니다.

답변

2

숫자가 커지면 시간이 지남에 따라이 속성을 추적하기가 어려울 수 있습니다.

는 그냥 자동으로 덮어 쓰기하지 않을 속성을 추적 newFoo의 기능을 추가하는 방법을 만들 수

: 여기 arguments.length을 사용했습니다

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) 
    } 

}; 

는 매개 변수인지 확인 합격 한 경우 undefined에 대해 테스트하거나 always-truthy 속성에 대해 간단하게 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 
} 

에 'A'기능은이 문제를 밖으로 정렬해야한다.

prop 인수를 추가하지 않으면 isOnundefined으로 설정됩니다. 그래서 undefined을 출력으로 얻습니다.

+0

나는 당신이 그 질문에 대해 오해했다고 생각합니다. 나는 그것을 알고 플러스'정의되지 않은'거짓이다 ... 내가 원하는 것은 어떻게 든 가능하다면 실제로 모든 새로운 인스턴스에 이전 값을 전달하지 않고도'prop'를 계속 전달하는 것입니다/아마도 다른 접근 방법일까요? – elclanrs