2014-03-12 2 views
0

왜 내가 그런 일을 할 수 없습니까?Javascript RegExp as property

var obj = { 
    prop1:"a", 
    prop2:"b", 
    test1: new RegExp(this.prop1), 
    test2: new RegExp(this.prop2), 
    init: function(){ 
      if(this.test1.test('apple')){ 
       //code will be executed 
      } 
      if(this.test1.test('banana')){ 
       //code will be executed 
      } 
      if(this.test2.test('apple')){ 
       //code will be executed 
      } 
      if(this.test2.test('banana')){ 
       //code will be executed 
      } 
    } 
}; 
obj.init(); 

시험은 항상 /(?:)/이기 때문에 true를 반환합니다. 이 문제를 해결하는 방법? 좋아

http://jsfiddle.net/jk8MK/

+1

은 무엇 정확히 수행 할? 귀하의 질문은 무엇인가 ? – tnanoba

+0

정확히 무엇을하고 싶습니까? 귀하의 질문은 무엇인가 ? 친구 – Neel

+0

@ 오닐, 나는 '친구'하하를 놓쳤다 – tnanoba

답변

2

사용 기능 모두를 일치시킬 수 있습니다 // 그래서 :

var obj = { 
    prop1:"a", 
    prop2:"b", 
    test1: function() 
    { 
     return new RegExp(this.prop1); 
    }, 
    test2: function() 
    { 
     return new RegExp(this.prop2); 
    }, 
    init: function(){ 
      if(this.test1().test('apple')){ 
       console.log('1'); 
      } 
      if(this.test1().test('banana')){ 
       console.log('2'); 
      } 
      if(this.test2().test('apple')){ 
       console.log('3'); 
      } 
      if(this.test2().test('banana')){ 
       console.log('4'); 
      } 
    } 
}; 
obj.init(); 

http://jsfiddle.net/jk8MK/2/

+0

그리고 test1과 test2를 속성으로 저장하는 방법은 obj에서 null이되게하고 regexp를 init()에 할당하는 것입니다. function ... –

+0

또는 test1/2가 객체 속성으로 필요하지 않은 경우 로컬 변수 만 사용할 수 있습니다. http://jsfiddle.net/jk8MK/3/ – tarmaq

2

나는 내 일이 뭐죠 알려해야합니다 prop1에 포함 된 문자열은 정규식 부분을 사용할 수 없습니다 형성된 정규식 대신 사과와 바나나