2017-03-06 4 views
0

내가 실행하는 다음 코드를 작성했습니다와 방법을 정의 할 수 없습니다 개인 메소드로 정의됩니다. 그러나, 다음과 같은 정의가 작동하지 않습니다 : 나는 thisinitFolder을 정의 할 수없는 이유를은 "이"

this.init = function() { 
     this.initFolder() 
     ... 
    } 

    this.initFolder = function() { 
     // the code inside does not mention "this" 
     ... 
    } 

는 아는 사람 있나요?

+0

확인하십시오 :

특정 경우

당신은 같은 일을 할 수 있습니다 –

답변

1

이것은 this이 javascript의 박스 범위 내에서 작동하는 방식과 관련이 있습니다.

예 :

var obj = { 
    firstname: "rahul", 
    lastname: "arora" 
    getName: function(){ 
     console.log(this);//will output the object as this here points to the object it is defined under 
    } 
}; 

obj.getName(); 

방법 자바 스크립트 작품이다

var obj = { 
    firstname: "rahul", 
    lastname: "arora" 
    getName: function(){ 

      function getFullName(){ 
       console.log(this);//this refers to the window and not to the object this time 
      } 
      getFullName(); 
    } 
}; 

obj.getName(); 

반면. 조금 이상하지만이 방법이 설계되었습니다. 당신이 사용할 수있는 객체의 인스턴스를 만들기 위해 생성자 함수를 호출하지만 AngularJS와 서비스는 서비스를 호출 할 때

, 당신이하고있는 아무것도 동일한 개념을 적용

.

사용하는 모든 메소드는 사용자가 사용하는 컨트롤러에 전달 된 객체 인스턴스에 연결됩니다.

이제 해당 서비스의 바로 아래에 있지 않은 개체 내부에 함수가 정의되어있는 경우 위에 설명 된 개념 때문에 올바르게 작동하지 않습니다.

따라서이 값을 함수 내에서 사용하려면 변수의 값을이 변수에 저장해야합니다. 내 대답은 당신의 의심을 지 웁니다 경우

var self = this; 

this.init = function() { 
    self.initFolder() 
    /*since the function is called from inside a function which is inside an object, 
    this will not point to that instance of the object in this scenario. 
    Therefore, you have to store the value of this in a variable to make sure you use that inside this function to make it work properly.*/ 
    ... 
} 

this.initFolder = function() { 
    // the code inside does not mention "this" 
    ... 
} 
2

함수 외부에서 this에 대한 참조를 만들고이를 함수 내에서 사용하십시오. 이 방법을 사용하면 함수를 정의 할 때 this에 대한 참조가 있고 함수 내에서 해당 참조가 다시 사용됩니다. 그렇지 않으면 this은 메소드가 실제로 브라우저 윈도우와 같이 호출 될 때 다른 시점을 가리킬 수 있습니다. 내가 How does the "this" keyword work?을 통해 읽어 보시기 바랍니다

var me = this; 
this.init = function() { 
    // reference to this 
    me.initFolder() 
    ... 
} 

, 그것은 매우 잘 쓰여진 대답이있다.

관련 문제