2014년 6월 16일 월요일

[JavaScript] this 의 용법

this 키워드는 JavaScript 코드를 가지고 있는 객체를 지칭한다. 
function에서 사용 되는 경우 그 function 을 가지고 있는 객체를 지칭하고 객체에서 사용하면 객체 자체를 가르킨다. 

<script>
function Person (name, age) {
    this.name = name;
    this.age = age;

    this.sayHello = function () {
          var name = "Person";
          return this.name +  " : Hello " + name + ".";
    }
}

var smith = new Person("smith", 37);
console.log (smith.sayHello ()); // smith : Hello Person.
</script>

위의 예제에서 출력 결과는 "smith : Hello Person.”이다.


Person 바로 아래에 있는 this 는 현재 코드를 소유한 객체(smith)를 지칭하게 되고 sayHello 아래에서 this 는 function 소유한 객체를 가키게 된다. 즉, smith 이다.
따라서 sayHello 함수에서의 this는 함수 자신이 아닌 smith이다. 그래서 this.name은 “smith” 가 되고 name은 함수 내부의 변수 “Person”을 가르키게 된다. 

이와 비슷한 형태로 혼동하기 쉬운 상황이 있다. 

<script>
function civil() {
    var name = "Neo";

    function sayMyName() {
         console.log ("name : " + name); // name : Neo
         console.log ("this.name : " +  this.name); // this.name : 
    }
    sayMyName();
}
    
civil();
</script>

이와 같은 경우는 function 에서 사용되는 경우이다. 
현재 civil() 을 실행 시키는 주체 window 이므로 코드를 소유한 객체는 window 가 된다 따라서 this 키워드는 window 객체를 가르 키게 된다. 
따라서 이 경우 this.name 은 내용이 없어서 안찍게 된다. 
실제로  civil(); 을 window.civil(); 로 해도 동일하게 동작하게 된다.  



댓글 없음:

댓글 쓰기