ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 객체 - 메서드와 this
    Javascript 2021. 7. 3. 16:50

    객체 프로퍼티에 할당된 함수를 메서드라고 부르고

    메서드 내부에서 this 키워드를 사용하면 객체에 접근할 수 있다.

    이때 점 앞의 this는 메서드를 호출할 때 사용된 객체를 나타낸다.

    let user = {
      name: "John",
      age: 30,
      
      sayHi: function() {
        // 'this'는 '현재 객체'를 나타냅니다.
        alert(this.name);
      }
    
    };
    
    user.sayHi(); // John

     

    여기서 sayHi는 user에 할당된 메서드이다.

     

     

    this값은 런타임에 결정된다.

    자바스크립트에서는 모든 함수에 this를 사용할 수 있다.

    동일한 함수라도 다른 객체에서 호출됐다면 'this'가 참조하는 값이 달라진다.

    let user = { name: "John" };
    let admin = { name: "Admin" };
    
    function sayHi() {
      alert( this.name );
    }
    
    // 별개의 객체에서 동일한 함수를 사용함
    user.f = sayHi;
    admin.f = sayHi;
    
    // 'this'는 '점(.) 앞의' 객체를 참조하기 때문에
    // this 값이 달라짐
    user.f(); // John  (this == user)
    admin.f(); // Admin  (this == admin)
    
    admin['f'](); // Admin (점과 대괄호는 동일하게 동작함)

    여기서 this는 각각 점 앞의 객체인 user객체와 admin객체를 참조하게 된다. 따라서 alert(this.name)이 결과값이 John, Admin가 나온다.

     

    화살표함수에는 this가 없어서 화살표함수에서 this를 참조하면 화살표 함수가 아닌 평범한 외부 함수에서 this값을 가져온다.

    let user = {
      firstName: "보라",
      sayHi() {
        let arrow = () => alert(this.firstName);
        arrow();
      }
    };
    
    user.sayHi(); // 보라

    함수 arrow()에서 this가 쓰였지만 화살표 함수라서 this는 외부함수인 sayHi()의 this가 되고, 이때 this는 객체 user를 가리키므로

    this.firstName = user.firstName =  "보라" 이다.

     

     

    문제

    1. 계산기 만들기

    calculator라는 객체를 만들고 세 메서드를 구현해 봅시다.

    • read()에선 프롬프트 창을 띄우고 더할 값 두 개를 입력받습니다. 입력받은 값은 객체의 프로퍼티에 저장합니다.
    • sum()은 저장된 두 값의 합을 반환합니다.
    • mul()은 저장된 두 값의 곱을 반환합니다.

     

    풀기

    let calculator = {
    
        read: function() {
            this.numberOne = +prompt('첫 번째 숫자 입력','숫자');
            this.numberTwo = +prompt('두 번째 숫자 입력','숫자');
        },
    
        sum: function() {
            return this.numberOne + this.numberTwo;
        },
    
        mul: function() {
            return this.numberOne * this.numberTwo;
        }
    };
    
    calculator.read();
    alert( calculator.sum() );
    alert( calculator.mul() );

     

    2. 체이닝

    up과 down 메서드를 제공하는 객체 ladder이 있다.

    let ladder = {
      step: 0,
      up() {
        this.step++;
      },
      down() {
        this.step--;
      },
      showStep: function() { // 사다리에서 몇 번째 단에 올라와 있는지 보여줌
        alert( this.step );
      }
    };
    
    ladder.up().up().down().showStep(); // 1 

    마지막 줄 처럼 메서드 호출 체이닝이 가능하도록 작성해보자.

     

     

    let ladder = {
      step: 0,
      up() {
        this.step++;
        return this;
      },
      down() {
        this.step--;
        return this;
      },
      showStep: function() { // 사다리에서 몇 번째 단에 올라와 있는지 보여줌
        alert( this.step );
      }
    };
    
    ladder.up().up().down().showStep(); // 1 

    ladder.up, ladder.down의 결과값이 ladder객체가 되야 하므로 up,down 메서드에 return this; 를 추가하면 객체를 반환하는 메서드 생성 완료

     

     

     

     

     

     

     

     

     

     

Designed by Tistory.