2 분 소요

this

this는 함수 내에서 함수 호출 맥락(context)를 의미한다. 맥락이라는것은 상황에 따라서 달라진다는 의미인데 즉 함수를 어떻게 호출하느냐에 따라서 this가 가리키는 대상이 달라진다는 뜻이다.

this는 함수와 객체의 관계간 연결시켜주는 실질적인 연결점의 역할을 한다.

        function func(){
            if(window === this){
                document.write("window === this");
            }
        }
        func();

위 예제를 실행했을때 this는 전역객체인 window와 같다는 것을 알 수 있다.

메소드의 호출

        var o = {
            func : function(){
                if(o === this){
                    document.write("o === this");
                }
            }
        }
        o.func();

위 예제를 실행하면 o === this 즉, this는 객체의 자기 자신을 가리킨다.

맨 위 예제도 사실 window가 생략됬을뿐, window.func(); 이며 같은 예제라 볼 수 있다.

생성자와 this

        var funcThis = null;
        function Func(){
            funcThis = this;
        }
        var o1 = Func();
        if(funcThis === window){
            document.write('window </br>');
        }

        var o2 = new Func();
        if(funcThis === o2){
            document.write('o2 <br>');
        }

위 예제에서 생성자 new의 빠짐의 차이점을 보고있다.

o1은 함수로만 호출한 것이고, o2는 생성자를 이용하여 호출한 것이다.

new를 추가하면 Func()는 생성자가 되어 새로운 객체를 생성한다.

  • 함수가 생성자로 사용될 경우, this는 생성될 객체를 가리킨다.
  • 함수로 호출한다면 this는 window를 가리킨다.

객체로서 함수

function sum(x,y){return x+y;}
sum(1,2);
var sum2 = new Function('x','y','return x+y;');
sum2(1,2);

위 결과는 똑같이 3으로 실행된다. 하지만 두 번째는 return 부분이 길어지면 사용하기 힘들다는 점이 있다. sum(x,y){return x+y;} 는 sum이라고 하는 함수 객체를 만든것이다.

  • function sum(x,y){return x+y;} // 함수 리터럴
  • var o = { } 객체 리터럴
  • var a = [1,2,3] 배열 리터럴

상속

상속은 객체의 로직을 그대로 물려 받는 또 다른 객체를 만들 수 있는 기능을 의미한다.

단순히 물려받는 것이라면 의미가 없을 것이다. 기존의 로직을 수정하고 변경해서 파생된 새로운 객체를 만들 수 있게 해준다.

        function Person(name){
            this.name = name;
        }
        Person.prototype.name=null;
        Person.prototype.introduce = function(){
            return 'My name is ' + this.name;
        }
        function Programmer(name){
            this.name = name;
        }
        Programmer.prototype = new Person();

        var p1 = new Programmer('weekbook');
        document.write(p1.introduce() + "<br>");

Programmer 함수에는 introduce가 따로 만들어져있지 않지만 사용하고있다.

이는 Person함수에서 prototype를 이용하여 상속할 속성들을 지정해놓고있으며,

Programmer.prototype = new Person(); 을 통하여 Person객체를 상속받고 있기 때문이다.

기능의 추가

        function Person(name){
            this.name = name;
        }
        Person.prototype.name=null;
        Person.prototype.introduce = function(){
            return 'My name is ' + this.name;
        }
        function Programmer(name){
            this.name = name;
        }
        Programmer.prototype = new Person();
        Programmer.prototype.coding = function(){
            return "hello world";
        }
        function Designer(name){
            this.name = name;
        }
        Designer.prototype = new Person();
        Designer.prototype.design = function(){
            return "beautiful";
        }

        var p1 = new Programmer('weekbook');
        document.write(p1.introduce() + "<br>");
        document.write(p1.coding()+"<br>");

        var p2 = new Designer('hello');
        document.write(p2.introduce() + "<br>");
        document.write(p2.design()+"<br>");

Programmer과 Designer 객체는 Person의 상속을 받았다.

여기에 각각 coding과 design이라는 속성을 추가하여 같은 person의 상속을 받았지만 각 객체의 고유의 속성을 사용하여 출력하는 예제이다.

객체 고유의 속성을 추가하였기때문에 coding과 design의 메소드 부분을 바꾸어도 그 객체만 변변경되는것을 볼 수 있다.

두 객체 Person을 상속받았기때문에 introduce속성의 메소드를 변경하면 둘 다 적용된다.

댓글남기기