-
자바 스크립트의 클래스(class)와 객체(Object) 활용프론트엔드/JavaScript 2020. 9. 11. 04:51
자바 스크립트의 클래스 활용
자바 스크립트도 자바처럼 클래스(class)와 객체(Obejct)를 갖는다.
하지만 자바스크립트의 클래스는 ES6에 새로 추가된 개념이다.
클래스가 있기전 클래스를 통해 객체를 사용하지 않고 직접 객체를 만들어서 사용했다.
그리고 이런 객체를 복제하여 사용하며 이것을 상속의 개념으로 사용했다.
하지만 자바 스크립트에서도 클래스 사용이 가능해지면 자바의 문법과 비슷하게 구현이 가능하다.
자바 스크립트의 클래스 작성
자바 스크립트의 경우 자바와 비슷하게 대부분이 진행된다.
아래는 자바 스크립트에서 클래스를 선언하고 생성자로 객체를 생성하는 과정이다.
<script> class person{ // 클래스 선언 publicField = "퍼블릭"; // 퍼블릭 필드 #privateField = "프라이빗"; // 프라이빗필드 (클래스 밖에서 출력 불가) static staticField= "스태틱"; // 스태틱필드 constructor(name, age){ // 생성자 함수 this.name = name; this.age = age; } get age(){ // getter return this._age; } set age(value){ // setter if (value < 0){ throw Error("나이가 어려요"); } this._age = value < 0 ? 0: value; } } let student1 = new person ("철수", 20); // 객체 생성 console.log(student1.name); // "철수" 출력 console.log(student1.age); // '20' 출력 console.log(student1.publicField); // '퍼블릭' 출력 console.log(person.staticField); // '스태틱' 출력 </script>
자바 스크립트 클래스의 상속과 다형성, 오버라이딩
자바스크립트의 클래스도 이제 상속이 가능하고 이를 통해 자바의 기능을 그대로 구현가능하다.
아래는 도형을 그려주는 클래스를 만들고 그 클래스를 상속받아서 도형별로 다르게 그림을 그리는 클래스를 만들어준 뒤 활용하는 것이다.
<script> class Shape { //shape 객체 생성 constructor(width, height, color){ // 생성자 함수 선언 this.width = width; this.height = height; this.color = color; } draw(){ // draw 함수 선언 console.log(`drawing ${this.color} color of`); } getArea(){ // getArea 함수 선언 return this.width * this.height; } } class Reatangle extends Shape{} // shape를 상속 받아서 만든 클래스 class Triangle extends Shape{ // shape를 상속 받아서 만든 클래스 draw(){ // shape 클래스의 draw 함수 오버라이딩 super.draw(); // 부모 클래스 shape의 draw 함수 호출 console.log('△'); // 오버라이딩해서 새로 재정의한 함수의 내용 } getArea(){ // shape 클래스의 getArea 함수 오버라이딩 return (this.width * this.height) / 2; } } const rectangle = new Reatangle(20, 20, 'blue'); // Reatangle클래스의 객체 생성 rectangle.draw(); console.log(rectangle.getArea()); const triangle = new Triangle(20, 20, 'white'); // Triangle클래스의 객체 생성 triangle.draw(); console.log(triangle.getArea()); // instance of는 객체(Object)가 어떤 클래스를 통해 만들어졌는지 여부 확인 가능 console.log(rectangle instanceof Reatangle); // true console.log(triangle instanceof Reatangle); // false console.log(triangle instanceof Triangle); // true console.log(triangle instanceof Shape); // true: Shape 클래스를 상속 받아서 true console.log(triangle instanceof Object); // true: 자바스크립트의 모든 Object 클래스는 자바스크립트의 Object을 상속받아 만들어진다 // 자바스크립트의 모든 Object 객체는 자바스크립트의 Object를 상속받아 만들어진다. </script>
'프론트엔드 > JavaScript' 카테고리의 다른 글
자바스크립트의 전역 객체(Global object) (0) 2020.09.14 자바 스크립트의 객체(Object) (0) 2020.09.11 자바와 자바스크립트 클래스와 오브젝트 (0) 2020.09.11 자바스크립트 함수와 매개변수, 인수 (0) 2020.09.10 자바스크립트의 함수(function) (0) 2020.09.10