#14. 객체 지향 프로그래밍(3)

2langk·2021년 3월 22일
0

[오분자스 - 개념편]

목록 보기
14/24
post-thumbnail

Object Oriented Programming(4)

지난 시간에는 prototype을 활용해서 메소드의 중복을 피하는 방법을 알아보았다.
이번에는 prototype에 메소드를 정의할 때 주의할 점에 대해 알아보도록 하자.

예시1)

const Student = function(name, age) {
  this.name = name;
  this.age = age;
}

Student.prototype.sayHello = function() {
  return `${this.name} says Hello!`
}

const student1 = new Student('lee', 20);
const student2 = new Student('kim', 21);

student1.sayHello() // "lee says Hello!"
student2.sayHello() // "kim ~"

1) 프로토타입에 메소드에서 객체에 접근하려면 this 키워드를 사용한다.
실행 컨텍스트를 설명하면서 함수에서 this 키워드는 함수를 호출한 객체라고 언급 했었는데, 여기선 이것만 알고 있으면 된다.

student1.sayHello() 
// sayHello를 student1이 호출했으므로 this는 student1이 된다.

student2.sayHello()
// sayHello를 student2이 호출했으므로 this는 student2이 된다.

예시2)

Student.prototype.goHome = () => {
  return `${this.name} is going home`
}

student1.goHome() // " is going home"
student2.goHome()// " is going home"

// this.name이 undefined가 되버렸다...

2) 프로토타입 메소드는 arrow function을 사용하면 안된다.
자바스크립트를 공부하다보면 ES6에 등장한 arrow function을 종종 본다.
arrow function은 일반 function과 완전히 동일하지 않다. 그렇기 때문에 일반 function이 사라지지 않는 것이다.
대표적으로 arrow function의 this 키워드의 동작이 일반 function과 다르다.
그렇기 때문에, 프로토타입 메소드는 일반 function을 써야한다 정도로 기억하고 넘어가자.


이번엔 prototype에 메소드를 정의할 때 주의할 점에 대해 알아봤다.
다음에는 OOP의 특성중 하나인 상속에 대해 설명해야겠다.

0개의 댓글