Script
class와 object 본문
Class: 클래스는 붕어빵을 굽는 틀(템플릿)
class에서는 이 틀에는 ~~이 들어갈수 있다라는 틀의 모양만 잡음
Object: class안에 데이터를 넣어 만들어 진것이 object(객체)
class는 틀만 잡은 것이기에 메모리에 저장되지 않으나
object는 직접적인 결과물이므로 메모리에 저장됨
1.Class 선언
생성자,필드,메소드로 구성
class Person {
constructor(name,age){ //생성자
this.name=name;//필드
this.age=age;
}
//메소드
speak(){
console.log(`${this.name}:hello!`);
}
}
2.object 생성
틀안에 반죽넣는 과정
변수명=new class명();
const A= new Person('A',20);
console.log(A.name);//A
console.log(A.age);//20
A.speak();//A:hello!
3.Getter and setters
사용 의의
class User {
constructor(firstName,lastName,age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
}
const user1 = new User('Steve','Job',-1);
console.log(user1.age);//-1
//근데 age가 -1이 되는 것이 말이 안됌
//사용자가 실수로 나이에 -1을 입력하더라도 두고봐서는 안될노릇
//이를 get set으로 방지하는 것
그에 따른 getter setter 사용예시
class User {
constructor(firstName,lastName,age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
//get에서는 값을 return하고
get age() {
return this._age;//무한 loop되는 것을 방지하기 위해서
//getter와 setter에서 쓰여지는 변수명을 다르게 써야한다
//주로 _를 붙여 차별화
//이로 인해 필드에는 .age가아닌 _age가 들어가게됌
}
//set에서는 값을 설정한다
set age(value){
if (value<0) {
throw Error('age can not be negative');
}
this._age = value;
}
}
const user1 = new User('Steve','Job',-1);
console.log(user1.age);//age can not be negative
필드에는 _age가 있지만 .age를 사용할 수 있는 것,
.age에 값을 할당할 수 있는 것은
내부적으로 getter와 setter를 이용하기 때문이다.
4.Fields(piblic,private)
constructor를 사용하지 않아도 된다
그냥 쓰면 public이고 #과 함께 쓰면 private화 된다
public은 클래스 내부와 외부에서 모두 사용 가능하고
private는 클래스 내부에서만 사용 가능하다
class Experiment {
publicField = 2;
#privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publicField);//2
console.log(experiment.privateField);//undefined
5.Static
object에 상관없이 공통적으로 class에서 쓸 수 있는 것이라면
static과 static 메소드를 이용하는 것이 메모리의 사용을 줄여줄 수 있다
class Article{
static publisher = 'Dream Coding;'
constructor(articleNumber){
this.articleNumber = articleNumber;
}
static printPublisher() {
console.log(Article.publisher);
}
}
const article1 = new Article(1);
const article2=new Article(2);
console.log(Article1.publisher);//undefined
console.log(Article.publisher);//Dream coding
Article.printPublisher();//Dream coding
//static은 오브젝트마다 할당되는 것이 아닌
//class에 붙어있는것
6.상속 & 다양성
6-1.한 클래스를 다른 클래스로 확장하는 방법(상속)
class shape{
constructor(width,height,color){
this.width = width;
this.height = height;
this.color = color;
}
draw(){
console.log(`drawing ${this.color} color of`);
}
getArea() {
return this.width * this.height;
}
}
//Rectangle이라는 클래스를 Shape라는 클래스로 연장(extends)
class Rectangle extends Shape {}
class Triangle extends Shape{}
const rectangle = new Rectangle(20,20,'blue');
rectangle.draw();//drawing blue color of
const triangle = new Triangle(20,20,'red');
rectangle.draw();//drawing red color of
6-2.넓이를 구하는 getArea 메소드를 사용시
getArea() {
return width * this.height;
}
}
const rectangle = new Rectangle(20,20,'blue');
rectangle.draw();//drawing blue color of
console.log(rectangle.getArea());//400
const triangle = new Triangle(20,20,'red');
rectangle.draw();//drawing red color of
console.log(triangle.getArea());//400
//retagle과 triangle 결과가 둘다 400이 된다
//triangle의 널이를 구하는 공식을 따로 지정해줘야 한다는 것을 알 수 있다
해결방법(다양성)
getArea() {
return this.width * this.height;
}
}
class Rectangle extends Shape {}
class Triangle extends Shape {
getArea() {
return (this.width * this.height)/2;
}//필요한 함수만 재정의하여 사용할 수 있다(이를 Overridding이라고 함)
}}
const rectangle = new Rectangle(20,20,'blue');
console.log(rectangle.getArea());//400
const triangle = new Triangle(20,20,'red');
console.log(triangle.getArea());//200
6-3.super
draw(){
console.log(`drawing ${this.color} color of`);
}
class Rectangle extends Shape {}
class Triangle extends Shape {
draw() {
console.log('🔺');
}
}
//🔺
//부모값 까지 출력하고 싶다면
class Rectangle extends Shape {}
class Triangle extends Shape {
draw() {
super.draw();
console.log('🔺');
}
}
//drawing red color!
//🔺
7.instanceOf
왼쪽에 있는 것이 오른쪽에 속하는 것인지 참과 거짓으로 판별
console.log(rectangle instanceof Rectangle);//t
console.log(triangle instanceof Rectangle);//f
console.log(triangle instanceof Triangle);//t
console.log(triangle instanceof Shape);//t
console.log(triangle instanceof Object);//t(js에서 사용하는 모든 객체와 class는 이 Object를 상속한 것이다)
'Javascript' 카테고리의 다른 글
| 배열 (0) | 2022.06.15 |
|---|---|
| object란? (0) | 2022.06.14 |
| 함수 (0) | 2022.06.12 |
| 연산자, if, 반복문 (0) | 2022.06.11 |
| 데이터타입 (0) | 2022.06.11 |
Comments