Object Review

신동윤·2021년 10월 28일
0

class vs object

class는 조금 더 연관있는 데이터들을 한데 묶어놓는 컨테이너같은 역할.
has properties and functions. in other words, it has fields(속성) and methods(행동).
다시 말하자면, class는 조금 더 연관있는 데이터들을 묶어놓은, fields와 methods가 종합적으로 묶여있는 것.
Fields만 묶여있을때가 있는데, 그럴땐 data class 라고 부름.

-template; (틀: 이러이러한 데이터가 들어올 수 있어! 라고 정의(?)만 해놓는다.
-declare once; 한번만 선언.
-no data in;

object: class를 이용해서 데이터를 넣어서 만드는 것이 object이다!
-instance of a class
-created many times
-data in

Class는 객체를 만들기 위한 틀 이라고 생각해두면 좋을 것 같다.

how to decalre a class?
예시)

class Person{
	constructor(name, age) { // fields
  this.name = name;
  this.age = age;
	}
	speak() {
  	console.log(`${this.name}: hello!`);
  }
}

Has fields (name & age) and a method called 'speak'.

Declaring object;
1. 새로운 객체를 만들 때에는 new 키워드를 사용.
const josh = new Person('joshua', 27);
josh.speak(); >> speak 함수 호출.

  1. getter & setter;
    it is incapsulation; making a property private so that other people cannot change it?
    커피머신 자판기 프로그램 예시) cannot make -1 cup of coffee. getter and setter will prevent others' mistakes typing wrong/inappropriate input?
    get & set 키워드를 사용.
get age() { //get 키워드를 이용해서 값을 리턴할 수 있다. 
	return this.age;
}
set age(value) { //set 키워드를 이용해서 값을 설정할 수 있다. 
	this.age = value; // set은 값을 설정하기 때문에 value를 받아와야한다. 
}

우리가 age라는 getter를 정의하는 순간 this.age는 메모리에 있는 age를 읽어오는 것이 아니라 getter를 호출.
우리가 setter를 정의하는 순간, this.age = age; 에서 값을 할당할 때, 메모리에 있는 값을 할당하는 것이 아니라 setter를 호출하게 됨. => call stack error.
in order to prevent such error, use different names for the variables in getter&setter. 아래에 올바른 예시;

```
set age(value){
if (value < 0) {
throw Error('age cannot be negative!');
}
this._age = value; 
or this._age = value < 0 ? 0: value; // 이게 제일 깔끔한 표현식.
}
```

Public & Private:
생성자를 쓰지않고 필드를 정의할 수 있는데, 그냥 정의하면 public, #을 앞에 붙이면 private.
private = class 내부에서만 값이 보여지고 접근이 가능하고 값 변경이 가능하나, 외부에서는 읽을수도 변경할 수도 없음. 출력시 undefined로 나옴.

상속&다양성

profile
응애 프로그래머(?)

0개의 댓글