on
JavaScript - 사용자 정의 객체 Class 정의
JavaScript - 사용자 정의 객체 Class 정의
사용자 정의 객체
사용자가 직접 필요한 객체를 생성해서 사용
사용자 정의 객체 생성 방법 리터럴 이용 생성자 함수(function()) 이용 new Object() 이용 class 정의하고 객체 생성
class 정의하고 객체 생성
class 키워드 사용
생성자 / Getters / Setters 사용 가능 Getters : 함수명 앞에 get이라고 붙이면 됨 프로퍼티 사용 시 앞에 언더바(_)를 붙여서 사용 Setters : 함수명 앞에 set이라고 붙이면 됨 프로퍼티 사용 시 앞에 언더바(_)를 붙여서 사용 Getter, Setter 호출 시 괄호 안 붙임 객체.메소드;
호이스팅 불가
형식
class 클래스명 { 생성자() { } Getters Setters 메소드(); } // 객체 생성 let 객체 = new 클래스명(); 객체.메소드();
class 정의 후 객체 생성 예제 - object6-Class.html
class Person { // 생성자 constructor(name, age) { // 프로퍼티 정의 this.name = name; this.age = age; } // Getter : 프로퍼티 반환 get name() { return this._name; } get age() { return this._age; } // Setter : 프로퍼티 값 설정 set name(name) { this._name = name; } set age(age) { this._age = age; } // 필요한 메소드 추가 toString() { return this.name + "은 " + this.age + "살 입니다."; } } // 호이스팅 불가 : 클래스 생성 이전 객체 생성 불가 let person1 = new Person("홍길동", 25); let person2 = new Person("이몽룡", 30); // getter 호출 console.log("성명 : " + person1.name + " 나이 : " + person1.age); // 성명 : 홍길동 나이 : 25 console.log("성명 : " + person2.name + " 나이 : " + person2.age); // 성명 : 이몽룡 나이 : 30 // toString() 메소드 호출 console.log(person1.toString()); // 홍길동은 25살 입니다. console.log(person2.toString()); // 이몽룡은 30살 입니다 // setter 호출 : 괄호 없음 person1.age = 27; console.log(person1.toString()); // 홍길동은 27살 입니다. person2.name = "성춘향"; person2.age = 20; console.log(person2.toString()); // 성춘향은 20살 입니다.
Class 정의 후 객체 생성 연습 문제 - object7-ClassEx.html
class Rectangle { constructor(width, height) { this.width = width; this.height = height; } get width() { return this._width; } get height() { return this._height; } set width(width) { this._width = width; } set height(height) { this._height = height; } getArea() { return "사각형의 넓이 : " + this.width*this.height; } } let rectangle1 = new Rectangle(); rectangle1.width = 30; rectangle1.height = 10; console.log("가로길이 : " + rectangle1.width + " 세로 길이 : " + rectangle1.height); console.log(rectangle1.getArea()); rectangle1.width = 20; rectangle1.height = 30; console.log(rectangle1.getArea());
from http://5bong2-develop.tistory.com/105 by ccl(A) rewrite - 2021-12-13 15:27:54