2014-12-14 2 views
0

나는 백본 컬렉션 findWhere() 기능의 작동 방식을 이해하려고 노력했다, 나는 코드에서 이것을보고 : 난이것은 무엇을 의미합니까? 이 [ '발견'] (기능 (모델) {...})

// Return models with matching attributes. Useful for simple cases of 
    // `filter`. 
    where: function(attrs, first) { 
     var matches = _.matches(attrs); 
     return this[first ? 'find' : 'filter'](function(model) { 
     return matches(model.attributes); 
     }); 
    }, 

    // Return the first model with matching attributes. Useful for simple cases 
    // of `find`. 
    findWhere: function(attrs) { 
     return this.where(attrs, true); 
    }, 

return this[first ? 'find' : 'filter'](function(model) { 
    return matches(model.attributes); 
    }); 

이 부분 this['find'](function(model){ ... }) 실제로 무엇을 하는가 :이 부분이 무엇을 이해하려고? 불리언 first 양수이면

답변

3

자바 스크립트에서 점 표기법 대신 괄호 표기법을 사용할 수 있으며 대괄호 표기법은 그런 경우 매우 유용합니다. 그래서, 다음과 같다 :이 라인에서

foo.['bar'] 
foo.bar() 

: 첫 번째 값이 this.filter()가 사용되는 다른 true를 돌려주는 경우

return this[first ? 'find' : 'filter'](function(model) { 

this.find()가 사용됩니다. 이

return this[first ? 'find' : 'filter'](function(model) { 
    return matches(model.attributes); 
}); 

1

그것은이

  • this 같이가는 것은 Object

  • [first ? 'find' : 'filter'] 검사 된 다음 괄호 표기 [] 액세스 함수 참조있는 다른 'find''filter' 반환. bracker 표기법을 사용하여 함수 참조에 액세스하는 3 진 연산자의 짧은 사용법.

  • (...){}은 해당 기능을 호출합니다.

    this.find(function(model){ ... }) 
    

    그래서 답 :

1
this['find'](function(model){ ... }) 

이 부분은 동일이 매개 변수를 사용하여 호출되는 객체 this 방법 find이다 (나는 그것이 콜백 가정 :)) function(model){ ... }.

1

if(first){ 
    return this['find'](function(model) { 
     return matches(model.attributes); 
    }); 
} else { 
    return this['filter'](function(model) { 
     return matches(model.attributes); 
    }); 
} 
과 동일 어느

var functionName; 
if(first){ 
    functionName = 'find'; 
} else { 
    functionName = 'filter'; 
} 
return this[functionName](function(model) { 
    return matches(model.attributes); 
}); 

과 동일 어느

var functionName = (first ? 'find' : 'filter'); 
return this[functionName](function(model) { 
    return matches(model.attributes); 
}); 

과 동일 내가 그 그것을 정리할 희망

if(first){ 
    return this.find(function(model) { 
     return matches(model.attributes); 
    }); 
} else { 
    return this.filter(function(model) { 
     return matches(model.attributes); 
    }); 
} 

과 동일

.

관련 문제