📝 [Section2_Unit2] 객체지향 프로그래밍 #1
객체지향 프로그래밍에 쓰이는 객체(자바스크립트의 object와는 다르다)를 클래스(class)
라고 한다. 클래스를 통해 만들어내는 객체는 인스턴스(instance)
가 된다.
클래스는 인스턴스가 만들어질 때 실행되며, 이런 함수를 생성자(constructor) 함수
라고 한다.
일반적인 다른 함수와 구별되게 하기 위해 클래스명은 대문자로 시작하고, 일반 명사 느낌으로 짓는다.
function Person(name) {...}
class Person{
constructor(name){
...
}
}
인스턴스가 만들어질 때 즉시 생성자 함수가 실행되며 변수에 인스턴스가 할당된다. 이렇게 만들어진 인스턴스는 클래스의 고유한 속성과 메서드를 그대로 갖는다.
let instance1 = new Person('hyesoo');
let instance2 = new Person('Jimmy');
속성(property)
은 객체 내부에 존재하는 값이며 자료형이 함수인 속성은 메서드(method)
라고 한다. 사람을 예로 들면 name, country를 속성으로 갖고 eat을 메서드로 갖게할 수 있다.
function Person(name,country){
this.name = name;
this.country = country;
}
Person.prototype.eat = function() {
return `${this.name}가 음식을 먹었습니다.`
}
class Person{
constructor(name, country){
this.name = name;
this.country = country;
}
eat(){
return `${this.name}가 음식을 먹었습니다.`
}
}
const instance1 = new Person('hyesoo', 'Korea');
console.log(hyesoo.country); // Korea
console.log(hyesoo.eat()); // hyesoo가 음식을 먹었습니다.