Class 정의
ES6에 새로 추가된 문법 class
자바스크립트 Class는 Java와 같은 객체 지향언어와 같은 동작을 하는 것이 아닌 객체 지향의 일부개념을 활용하기 위한 "특별한 함수"이다. 함수를 함수 표현식과 함수선언으로 정의할 수 있듯이 class 문법도 class 표현식과 class 선언으로 정의할 수 있다.
Class 선언식
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
Class 표현식
class 표현식은 이름을 가질 수도 있고, 갖지 않을 수도 있다. 이름을 가진 class 표현식의 이름 클래스는 body의 local scope에 한해 유효하다. (하지만, 클래스의 name속성(인스턴스 이름이 아닌)을 통해 찾을 수 있다.)
// unnamed
let Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
console.log(Rectangle.name); // "Rectangle"
// named
let Rectangle = class Rectangle2 {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
console.log(Rectangle.name); // "Rectangle2"
Hoisting
함수 선언식과 클래스 선언식, 함수 표현식과 클래스 표현식의 중요한 차이점은 함수의 경우 정의하기 전에 호출할 수 있고, 클래스는 반드시 정의한 뒤에 사용할 수 있다.
즉, 함수는 호이스팅이되고 클래스는 그렇지 못한다는 점이다.
우선 클래스를 선언한 뒤에 접근해야 한다. 그렇지 않으면 아래와 같은 코드를 ReferenceError 를 출력할 것이다.
const p = new Rectangle(); // Reference Error
class Rectangle {}
Class body 와 메서드 정의
클래스 바디는 중괄호 { } 로 묶여 있는 부분, 메서드나 constructor와 같은 class 멤버를 정의하는 곳이다.
Strict mode
클래스의 본문(body)은 strict mode(엄격 모드)에서 실행된다.
[Javascript] 자바스크립트 strict mode(엄격 모드)에 대해
strict mode (엄격모드) 자바스크립트 언어의 문법을 좀 더 엄격히 적용하여 최적화 작업에 문제를 일으킬 수 있는 코드에 대해 명시적인 에러를 발생시키는 것이다. 'use strict'는 자바스크립트의 의
haenny.tistory.com
Constructor (생성자)
constructor 메서드는 class 키워드로 생성된 객체의 생성과 초기화를 위한 특별한 메서드이다. 하나의 클래스 안에는 constructor라는 이름을 가진 특별한 메서드는 오직 하나만 올 수 있다. 하나 이상의 constructor 메서드가 온다면 SyntaxError를 출력할 것이다.
부모 클래스의 constructor를 호출하기 위해 super 키워드를 사용할 수 있다.
Prototype methods
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// getter
get area() {
return this.calcArea();
}
// method
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
console.log(square.area); // 100
Static methods(정적 메서드) 와 properties(속성)
static 키워드는 클래스의 static method 와 static property 를 정의한다. Static 멤버는 이 클래스를 인스턴스화(instantiating)하지 않고 호출 되며, 클래스 인스턴스를 통해 호출하는 것이 불가능하다.
Static methods는 종종 애플리케이션을 위한 유틸리티 함수를 생성하기 위해 쓰이며, Static properties는 캐시나 fixed-configuration, 또는 인스턴스 전체에 복사될 필요가 없는 다른 데이터를 위해 유용하게 쓰인다.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static displayName = "Point";
static distance(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.hypot(dx, dy);
}
}
const p1 = new Point(5, 5);
const p2 = new Point(10, 10);
p1.displayName; // undefined
p1.distance; // undefined
p2.displayName; // undefined
p2.distance; // undefined
console.log(Point.displayName); // "Point"
console.log(Point.distance(p1, p2)); // 7.0710678118654755
프로토타입과 static methods로 this 를 바인딩하기
가령 변수에 메서드를 할당하고 이를 부르는 것처럼, static 또는 프로토타입 메서드를 this 를 위한 value 없이 호출했을 때, this 값은 메서드 내에서 undefined 일 것이다. 'use strict' 구문이 없어도 같은 반응이 나온다. class 바디는 항상 엄격 모드 내에서 실행되기 때문이다.
class Animal {
speak() {
return this;
}
static eat() {
return this;
}
}
let obj = new Animal();
obj.speak(); // the Animal object
let speak = obj.speak;
speak(); // undefined
Animal.eat(); // class Animal
let eat = Animal.eat;
eat(); // undefined
참고
Classes - JavaScript | MDN
Class는 객체를 생성하기 위한 템플릿입니다. 클래스는 데이터와 이를 조작하는 코드를 하나로 추상화합니다. 자바스크립트에서 클래스는 프로토타입을 이용해서 만들어졌지만 ES5의 클래스 의
developer.mozilla.org
'Front > JavaScript' 카테고리의 다른 글
[JavaScript] 문자열 특정 문자/정규 포현식 위치 찾기 (indexOf, search) (0) | 2022.04.07 |
---|---|
[JavaScript] 자바스크립트 날짜 문자열 포맷 반환 함수 만들기 (기본값 매개변수 설정하기) (0) | 2022.04.06 |
[Javascript] 자바스크립트 strict mode(엄격 모드)에 대해 (0) | 2022.03.17 |
[JavaScript] Custom URL schemes 방식의 VNC 응용프로그램 (서버IP 인자 값 넘기며) 호출 (0) | 2022.01.13 |
[JavaScript] 웹(Chrome)에서 응용 프로그램 실행 시키기 : Registry 이용한 Custom URL schemes 방식 호출 (0) | 2022.01.12 |
댓글