객체 지향 프로그래밍에 있어서 가장 중요한 것이다. 클래스(class)는 객체 안에 속성과 메서드를 가지고 있다. 이러한 클래스를 바탕으로 한 객체는 인스턴스(instance) 객체다.
클래스를 정의하는 방법은 일반적으로 함수를 정의하는 것과 비슷하다.
일반적인 함수의 형태로 정의
function Person(age, gender, height, name ) {
// 인스턴스가 만들어질 때 실행되는 코드 //
}
class
키워드를 이용해서 정의
class Person {
constructor(age, gender, height, name) {
// 인스턴스가 만들어질 때 실행되는 코드
}
}
ES6에서는 constructor
라는 생성자로 인스턴스가 만들어질 때 실행되는 부분을 나눴다. 생성자에는 return
을 쓰지 않는다.
인스턴스를 만들 때에는 new
키워드를 사용한다. 인스턴스를 만들면 생성자 constructor가 실행되며, 변수에 클래스의 구조를 가진 새로운 객체. 즉 인스턴스가 할당된다.
let teacher = new Person(25, Male, 178, "John")
let dad = new Person(40, Male, 180, "Tom")
let mom = new Person(35, Female, 160, "Lisa")
let me = new Person(8, Male, 130, "Teddy")
각각의 인스턴스는 클래스의 고유한 속성과 메서드를 갖는다.
클래스 안에는 속성과 메서드가 있다. 속성을 가지고 메서드에 이용할 수 있다. 인스턴스들은 속성과 메서드를 이것을 이용한다.
function Person(age, gender, height, name ) {
this.age = age;
this.gender = gender;
this.height = height;
this.name = name;
Person.prototype.eat = function() {}
Person.prototype.sleep() = function() {}
Person.prototype.walk() = function() {}
Person.prototype.breathe() = function() {}
}
ES5는 prototype
이라는 것은 이용해서 메서드를 정의했다.
class Person {
constructor(age, gender, height, name ) {
this.age = age;
this.gender = gender;
this.height = height;
this.name = name;
}
eat() {}
sleep() {}
walk() {}
breathe() {}
}
this
키워드는 인스턴스 객체 자체를 의미한다. this를 사용하여 객체 안에서 쓰일 변수들을 선언해주는 것이다.
let teacher = new Person(25, Male, 178, "John")
teacher.age; // 25;
teacher.breathe(); // 후하후하~
let mom = new Person(35, Female, 160, "Lisa")
mom.walk(); // 터벅 터벅
참조
Classes in Javascript https://developer.mozilla.org/ko/docs/Learn/JavaScript/Objects/Classes_in_JavaScript
new operator
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/new
객체로 작업하기
https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Working_with_objects