function Person(name) {
this.name = name;
}
Person.prototype.sayHi = function () {
console.log(`Hi, I'm ${this.name}`);
};
const me = new Person('J');
me.sayHi(); // "Hi, I'm J"
class
문법은 기존 프로토타입 기반 패턴을 클래스 기반 패턴처럼 사용할 수 있도록 하는 함수(문법적 설탕)임class
와 생성자 함수의 차이점new
연산자와 함께 호출해야 하지만, 생성자 함수는 new
연산자가 없어도 일반 함수로서 호출됨extends
와 super
키워드를 제공함constructor
, 프로토타입 메소드, 정적 메소드는 모두 프로퍼티 어트리뷰트 [[Enumerable]]
이 false이기에 열거되지 않음class Person {}
const Person = class {};
const Person = class Class {};
constructor
, 프로토타입 메소드, 정적 메소드)만 정의할 수 있음class Person {
// 인스턴스 생성 및 초기화
constructor(name) {
this.name = name; // public
}
// 프로토타입 메소드
sayHi() {
console.log(`Hi I'm ${this.name}`);
}
// 정적 메소드
static sayHello() {
console.log(`Hi I'm ${this.name}`);
}
}
const me = new Person('J');
me.sayHi(); // // "Hi I'm J"
Person.sayHello(); // "Hi I'm Person"
constructor
임class Person {}
console.log(typeof Person); // function
let
, const
변수처럼 호이스팅 됨 (TDZ를 가짐)const Person = '';
{
console.log(Person); // error
class Person {}
}
cf) 모든 선언문은 런타임 이전에 실행됨
const Person = class Class {};
const me = new Person();
console.log(me); // Class {}
this
는 클래스가 생성한 인스턴스를 가리킴this
에 추가한 프로퍼티는 인스턴스 프로퍼티가 됨class Person {
constructor(name) {
this.name = name;
this.city = 'seoul';
}
}
const me = new Person('J');
console.log(me); // Person {name: 'J', city: 'seoul'}
단순한 메소드로 해석되지 않고, 클래스가 평가되어 생성한 함수 객체 코드의 일부가 됨. 즉 constructor
에 기술된 동작을 하는 함수 객체가 생성됨
한 개만 존재할 수 있음
생략 가능함
class Person {} // 아래처럼 빈 constructor가 암묵적으로 정의됨
class Person {
constructor() {}
}
cf) 프로토타입의 constructor
프로퍼티는 모든 프로토타입이 갖고 있는 프로퍼티로 생성자 함수를 가리키고, 클래스의 constructor
메소드와는 관련이 없음
class Person {
constructor(name) {
this.name = name;
}
sayHi() {
console.log(`Hi, I'm ${this.name}`);
}
}
const me = new Person('J');
console.log(Object.getPrototypeOf(me) === Person.prototype); // true
console.log(me instanceof Person); // true
console.log(Object.getPrototypeOf(Person.prototype) === Object.prototype); // true
console.log(me instanceof Object); // true
console.log(me.constructor === Person); // true
인스턴스를 생성하지 않아도 호출할 수 있는 메소드
class Person {
constructor(name) {
this.name = name;
}
static sayHi() {
console.log('Hi');
}
}
Person.sayHi(); // Hi
const me = new Person('J');
me.sayHi(); // TypeError: me.sayHi is not a function
class Sqaure {
constructor(width, height) {
this.width = width;
this.height = height;
}
// 정적 메소드
static area(width, height) {
return width * height;
}
// 프로토타입 메소드
area() {
return this.width * this.height;
}
}
Reflect.has({ a: 1 }, 'a');
function
키워드를 생략한 축약 표현을 사용함[[Enumerable]]
값이 false라 for in문 또는 Object.keys
로 열거할 수 없음new 연산자와 함께 클래스 호출 시, constructor 실행 이전에 인스턴스(빈 객체)가 생성되고, 인스턴스의 프로토타입으로 클래스의 prototype
객체가 설정됨. 그리고 인스턴스가 this에 바인딩 됨
constructor가 실행되어 this에 바인딩 된 인스턴스를 초기화 함
완성된 인스턴스가 바인딩 된 this가 암묵적으로 반환됨
class Person {
constructor(name) {
console.log(Object.getPrototypeOf(this) === Person.prototype); // true
this.name = name;
}
}