# 자바스크립트 (class vs object) 객체지향 언어

### class&#x20;

**연관있는 데이터를 묶어 놓는 역활을 해준다.**&#x20;

```javascript
class person{
name;
age;
speak();
}
// 속성 (field) 와 행동(method) 가 들어있음 
```

* template
* declare once
* no data in <- 정의만한것&#x20;

###

### object

**class를 이용해서 새로운 instance 생성하면 object가 된다.**

* instance of a class&#x20;
* created many times
* data in&#x20;

```javascript
'use strict';
// Object-oriendted programming
// object: instance of a class
// JavaScript classes 
// introduced in ES6
// syntactial suger over prototype-based inheritance


// 1. class declatations
class Person {
    // constructor
    constructor(name, age) {
        //fields
        this.name = name;
        this.age = age;
    }

    //methods
    speak() {
        console.log(`${this.name}: hello!`);
    }
}


//object 생성  
const ellie = new Person('ellie', 20); // 새로운 object 생성 
console.log(ellie.name); //ellie
console.log(ellie.age); // 20
ellie.speak(); // ellie: hello!

//2. Getter and stters 
class User {
    constructor(firstName, lastName, age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    //get이라는 키워드로 값을 리턴함 
    get age() {
        return this._age;
    }

    //set이라는 키워드로 값을 설정함 
    set age(value) {
        //if (value < 0) {
        //   throw Error('age can not be nagative')
        // }
        this._age = value < 0 ? 0 : value; 
    }
}
// 사람의 나이가 -1이될 수 없기때문에 이런것을 방지하기 위하여 getter와 stter을 사용하는것이다.
const user1 = new User('steve', 'Jap', -1);
console.log(user1.age);

```

###

### Getter and setters

```javascript
class User {
    constructor(firstName, lastName, age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    //get이라는 키워드로 값을 리턴함 
    get age() {
        return this._age;
    }
      

    //set이라는 키워드로 값을 설정함 
    set age(value) {
        //if (value < 0) {
        //   throw Error('age can not be nagative')
        // }
        this._age = value < 0 ? 0 : value; // -1이여도 0으로 출력됨
    }
 // age 값을 할당하는것이 아니라 setter을 호출하게 되기때문에 속성이름을 바꿔줘야한다.
}
// 사람의 나이가 -1이될 수 없기때문에 이런것을 방지하기 위하여 getter와 stter을 사용하는것이다.
const user1 = new User('steve', 'Jap', -1);
console.log(user1.age);
```

###

### Fields (public, private) / Static properties and methods

```javascript
//Fields (public, private) 
// Too soon! (사파리에서는 지원이 안되서 바벨을 이용해야함)
class Experiment {
    publicField = 2;
    #privaterField = 0;
    // 클래스 내부에서만 접근 가능 외부에서는 읽을 수 도 변경할 수 도 없음 
}
const experiment = new Experiment();
console.log(experiment.publicField); //2
console.log(experiment.privaterField); //undefined

//Static properties and methods
// Too soon!
class Article {
    static publisher = 'Dream coding';
    constructor(articleNumber) {
        this.articleNumber = articleNumber;
    }

    static printPublisher() {
        console.log(Article.publisher); //undefined undefined
    }
}
const article1 = new Article(1);
const article2 = new Article(2);
console.log(Article.publisher);
Article.printPublisher();
// static은 Atticle 에 값이 지정되있기떄문에 호출할때 클래스명을 이용해서 출력해야한다.
```

**들어오는 데이터(object)에 상관없이 공통적으로 class에서 쓸 수 있는것이라면 static과 static method를 이용하여  메모리의 사용을 줄일 수 있다.**&#x20;

###

### **상속 & 다양**성

```javascript
//상속, 다양성
// Inheritance
// a way for one class to extend another class.
class Shape {
    constructor(width, height, color) {
        this.width = width;
        this.heihgt = height;
        this.color = color;
    }
    // shape에는 width, height, color라는 flids가 있고 

    draw() {
        console.log(`drawing ${this.color} color!`);
    }
     // draw라는 메소드 
    getArea() {
        return this.width * this.heihgt;
    }
    // getArea 라는 메소드 
}

class Rectangle extends Shape { } 
//extends (연장한다) 을 이용하면 shape의 모든것들이 rectangle에 포함이됨 
class Triangle extends Shape {
    draw() {
        super.draw(); // 부모의 메소드도 포함이됨
        console.log('🔺');
    }
    // 오버라이딩 필요한 메소드를 재정비함 (필요한 함수만 오버라이딩해서 작성할 수 있다.)
    getArea() {
        return (this.width * this.heihgt) / 2;
    }

    toString() {
        return `Triangle: color: ${this.color}`;
    }
}

const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw(); // drawing blue color!
console.log(rectangle.getArea());//400
const triangle = new Triangle(20, 20, 'green');// drawing green color!
triangle.draw();// 🔺
console.log(triangle.getArea());//200
```

###

### instanceOf

```javascript
// 6. Class checking: instanceOf
console.log(rectangle instanceof Rectangle); //true
//rectangle(object)가 Rectangle(class)에서 만들어진것인지 확인하는 역활
console.log(triangle instanceof Rectangle); //false
console.log(triangle instanceof Triangle); //true
console.log(triangle instanceof Shape); //true
console.log(triangle instanceof Object); //true
console.log(triangle.toString()); // Triangle: color: red;
```

###

### 공부 참조사이트

<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://leeboa.gitbook.io/study/_/class-vs-object.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
