Javascript
[모자딥]Class
index.ys
2023. 12. 2. 18:24
예제 25.05
- 클래스는 함수로 평가됨
- 프로토타입과 생성자 함수는 단독으로 존재할 수없고 언제나 쌍으로 전재함
class Person { }
console.log(typeof Person); // function
예제 25.06
- 클래스는 클래스 정의 이전에 참조할 수 없음
console.log(Person);
// ReferenceError: Cannot access 'Person' before initialization
// 클래스 선언문
class Person { }
예제 25.07
- 클래스 선언문도 변수 선언, 함수정의와 같이 호이스팅 발생
- 클래스는 let,const키워드로 선언한 변수처럼 호이스팅됨 => TDZ에 접근했을때 RangeError 발생
const Person = '';
{
// 호이스팅이 발생하지 않는다면 ''이 출력되어야 한다.
console.log(Person);
// ReferenceError: Cannot access 'Person' before initialization
// 클래스 선언문
class Person { }
}
예제 25.08
- 클래스는 생성자 함수이며 new 연산자와 함께 호출되어 인스턴스를 생성한다.
- 클래스는 인스턴스를 생성하는 것이 유일한 존재 이유이므로 반드시 new 연산자와 함께 호출해야함
- Number, Array, String 등 내장 객체를 사용하여 인스턴스를 생성하는 것과 비슷한 개념
class Person { }
// 인스턴스 생성
const me = new Person();
console.log(me); // Person {}
const number = new Number();
const array = new Array();
const number = new String();
예제 25.09
- new 연산자 없이 호출하면 typeError 발생
class Person { }
// 클래스를 new 연산자 없이 호출하면 타입 에러가 발생한다.
const me = Person();
// TypeError: Class constructor Person cannot be invoked without 'new'
예제 25.10
- 기명 클래스 표현식의 클래스 이름을 사용해 인스턴스 생성하면 에러발생
- 클래스 표현식에서 사용한 클래스 이름은 외부 코드에서 접근 불가능
const Person = class MyClass { };
// 함수 표현식과 마찬가지로 클래스를 가리키는 식별자로 인스턴스를 생성해야 한다.
const me = new Person();
const Person1 = class { };
const me1 = new Person1();
console.log(me1) //Person1 {}
// 클래스 이름 MyClass는 함수와 동일하게 클래스 몸체 내부에서만 유효한 식별자다.
console.log(MyClass); // ReferenceError: MyClass is not defined
const you = new MyClass(); // ReferenceError: MyClass is not defined
예제 25.11
- 클래스 몸체에는 0개이상의 메서드만 선언할 수 있음
- 정의할 수 있는 메서드는 constructor( 생성자 ), 프로토타입 메서드, 정적 메서드가 있음
- constructor는 인스턴스를 생성하고 초기화하기 위한 특수한 메서드
class Person {
// 생성자
constructor(name) {
// 인스턴스 생성 및 초기화
this.name = name;
}
}
const person = new Person('내 이름은 짱구');
console.log(person.name) //내 이름은 짱구
예제 25.12
- 함수와 동일하게 프로토타입과 연결되어 있으며 자신의 스코프 체인을 구성함
- prototype 프로퍼티가 가리키는 프로토타입 객체의 constructor 프로퍼티는 클래스 자신을 가리킴 클래스가 인스턴스를 생성하는 생성자 함수라는 것을 의미
- new 연산자와 함꼐 클래스를 호출하면 클래스는 인스턴스를 생성함
class Person {
// 생성자
constructor(name) {
// 인스턴스 생성 및 초기화
this.name = name;
}
}
const person = new Person('내 이름은 짱구');
console.log(person.name) //내 이름은 짱구
// 클래스는 함수다.
console.log(typeof Person); // function
console.dir(Person);
예제 25.13
- 선언한 클래스는 new 연산자로 인스턴스를 생성함
// 인스턴스 생성
const me = new Person('Lee');
console.log(me);
예제 25.14
- 클래스 정의가 평가되면 constructor의 기술된 동작을 하는 함수 객체가 생성됨
class Person1 {
// 생성자
constructor(name) {
// 인스턴스 생성 및 초기화
this.name = name;
}
}
function Person2(name) {
// 인스턴스 생성 및 초기화
this.name = name;
}
const person1 = new Person1("짱구");
const person2 = new Person2("유리");
console.log(person1.name)//짱구
console.log(person2.name)//유리
예제 25.15
- constructor는 클래스 내에 최대 한 개만 존재가능 2개 이상은 문법에러 발생
class Person {
constructor() { }
constructor() { }
}
예제 25.16
- 빈 constructor 생성
class Person { }
const person = new Person();
console.log(person) //Person {}
예제 25.17
class Person {
// constructor를 생략하면 다음과 같이 빈 constructor가 암묵적으로 정의된다.
constructor() { }
}
// 빈 객체가 생성된다.
const person = new Person();
console.log(person); // Person {}
예제 25.18
- constructor에 초기화된 인스턴스 생성
- constructor에 매개변수로 초기값 전달
class Person1 {
constructor() {
// 고정값으로 인스턴스 초기화
this.name = 'Lee';
this.address = 'Seoul';
}
}
const person1 = new Person1();
console.log(person1); // Person1 {name: "Lee", address: "Seoul"}
class Person2 {
constructor(name, address) {
//인자로 인스턴스 초기화
this.name = name
this.address = address
}
}
//여기서 전달된 인자는 순서대로 생성자 함수에 할당
const person2 = new Person2('짱구', '일본');
console.log(person2); // Person2 { name: '짱구', address: '일본' }
예제 25.20
- constructor에는 return이 생략되어 있지만 명시적으로 return을 반환하면 암묵적인 this반환이 무시됨
class Person {
constructor(name) {
this.name = name;
// 명시적으로 객체를 반환하면 암묵적인 this 반환이 무시된다.
return {};
}
}
const person = new Person();
console.log(person)