2017-01-26 4 views
0

내 ajax 함수 내에서 this.chkOK를 설정할 수없는 것처럼 보입니다. 나는 일종의 솔직한 일이 어떻게 이렇게 나는 validateFields.call (this)이 내 문제를 해결해야한다고 생각하지만 그렇게하는 경우에 대해 알게되었다. 그래서 저는 다음 단계를 위해 무엇을해야할지 모릅니다. 내가하지 않으면 이것을 전역 변수로 설정하고 싶지 않습니다. 이걸 설정하려고합니다 .chkOK = true변수를 외부 함수로 설정할 수 없습니다.

function validateFields() { 

this.chkOK = null; 

this.username = function() { 
    if(FS.gID('username').value.length >= 2) { 

     var user = FS.gID('username').value; 


     //Make sure that the username doesn't already exist 
     FS.ajax('/server/chkUser.php?user='+user,'GET',function(){ 
      validateFields.call(this); 
      if(xmlText == 0) { 

        this.chkOK = true; 
       alert("This user doesn't exist."); 


      } 
      else if(xmlText == 1) { 
       alert("Theres already a user with this username"); 
       this.chkOK = false; 

      } 
     }); 

    } 
    else { 
     alert("empty"); 
     this.chkOK = false; 
    } 
alert(this.chkOK); 

} 
} 
+0

자신 만의 코드와이를 보는 다른 사람들의 코드를 모두 들여 쓰거나내어 쓰기해야합니다. –

답변

0

이것은 FS.ajax 내부가 작업하려는 의도와 같지 않기 때문입니다. this in FS.ajax는 다음을 의미합니다.

이 변수를 다른 변수에 할당하고 FS.ajax에서 사용할 수 있습니다. 예를 들어,

: 당신은 이유를 알지 못한다면 당신은 (예상 validateFields이 call 또는 apply에 의해 호출 등) this 원하지 않는 전역 객체 (인 함수 내에서 this.chkOk를 넣어 이유 에) 또는 엄격 모드에서 undefined 코드가 실패 할 것이다

function validateFields() { 

    this.chkOK = null; 

    // ** assign this to that. So you can reference it inside FS.ajax ** 
    var that = this; 

    this.username = function() { 
     if(FS.gID('username').value.length >= 2) { 
      var user = FS.gID('username').value; 

      //Make sure that the username doesn't already exist 
      FS.ajax('/server/chkUser.php?user='+user,'GET',function(){ 
       validateFields.call(this); 
       if(xmlText == 0) { 
        that.chkOK = true; // use `that` instead of `this`. 
        alert("This user doesn't exist."); 
       } else if(xmlText == 1) { 
        alert("Theres already a user with this username"); 
        that.chkOK = false; // use `that` instead of `this` 
       } 
      }); 
     } else { 
      alert("empty"); 
      this.chkOK = false; 
     } 

     alert(this.chkOK); 
    } 
} 
+0

상단에있는 'this.chkOK = null;'문에'this'가 무엇입니까? –

+0

솔직히 전체 코드가 보이지 않아서 모르겠다 ... 나는이 함수가 객체에 존재하기 때문에 코드에이 함수를 넣을 것이라고 기대한다. – gie3d

+0

함수 내에서'this'에 대한 알몸 참조는'call'이나'apply'로 호출하지 않는 한 전역 객체이거나 strict 모드 인'undefined'로 코드가 실패하게됩니다. if if 그는 그것이 함수의 지역 변수가된다는 것을 의미합니다. 여러분은 그것을 지적해야한다고 생각합니다. –

1

예제에서 this의 값은 코드에서 가정하는 것처럼 선언 된 함수가 아닙니다.

this.chkOK = null; 대신 var chkOK = null;을 사용하면 간단하게 작동합니다.

관련 문제