2023-05-13[TIL]

jenna·2023년 5월 13일
0

TIL/WIL

목록 보기
23/60

1.객체 리터럴


  • 객체(Object)
    • 원시 타입은 단 하나의 값만을 나타내고, 원시 타입의 값은 *변경이 불가능 한 값
    • 객체 타입은 다양한 타입의 값을 하나의 단위로 구성한 복합적인 자료 구조이고, 객체 타입의 값을 변경 가능한 값
  • 객체 리터럴로 객체 생성하기
    • 객체 리터럴은 중괄호 {} 내에 0개 이상의 프로퍼티를 정의해서 선언
let objectLiteral = {
    key: 'Value',
    helloWorld: function () {
        return "Hello world";
    }
};
  • 프로퍼티(Property) : 객체의 상태를 나타내는 , 프로퍼티는 (Key)와 (Value)으로 구성
const human = {
  // 프로퍼티 키: 'name', 프로퍼티 값: '이용우' 
  name: '이용우',
  // 프로퍼티 키: 'human age', 프로퍼티 값: 28 
  'human age': 28
}
  • 메서드(Method): 프로퍼티를 참조하고 조작할 수 있는 동작(behavior), 객체의 프로퍼티 값이 함수로 구성되어 있을 경우 메서드
let objectLiteral = {
    key: 'Value', // 프로퍼티
    helloWorld: function () { // 메서드
        return "Hello world";
    }
};

console.log(objectLiteral.helloWorld()); // Hello world

2.Error handling


  • try / catch
    • 서버에서 에러가 발생하지 않게 하기 위해서 저희는 예외 처리를 진행.
    • 에러가 발생하더라도 프로그램이 멈추지 않고 에러를 기록
const users = ["Lee", "Kim", "Park", 2];

try {
  for (const user of users) {
    console.log(user.toUpperCase());
  }
} catch (err) {
  console.error(`Error: ${err.message}`);
}

// LEE
// KIM
// PARK
// Error: user.toUpperCase is not a function

users에 들어있는 이름들을 String.toUpperCase()를 이용하여 대문자로 변경하려할 때 문자열(String)이 아닌 데이터가 들어온다면 에러

  • throw
    • 고의로 에러를 발생
    • throw를 호출하면 그 즉시 현재 실행되고 있는 함수는 실행을 멈춤.
function withdraw(amount, account) {
  if (amount > account.balance)
    throw new Error("잔고가 부족합니다.");
  account.balance -= amount;
	console.log(`현재 잔고가 ${account.balance}남았습니다.`); // 출력되지 않음
}

const account = { balance: 1000 };
withdraw(2000, account);

// Error: 잔고가 부족합니다.

계좌의 잔고가 요청받은 금액보다 적다면 현금 인출을 막고 예외를 발생시켜야한다
이럴때 사용하는 것이 throw

  • finally
    • try 에서는 특정한 ‘자원’을 가지고 처리할 때가 있다. 하지만 무의미한 메모리를 차지하게 될 것 이므로 에러 여부와 상관없이 일정 시점에서는 해당 ‘자원'을 삭제 시켜야한다.
    • finally는 에러가 발생했는지 여부와 상관없이 언제든지 실행됩니다.
function errorException(isThrow) {
  try {
    console.log('자원을 할당하였습니다.');
    if (isThrow) throw new Error();
  } catch (error) {
    console.log('에러가 발생했습니다.');
  } finally {
    console.log('자원을 제거하였습니다.');
  }
}

errorException(false);
// 자원을 할당하였습니다.
// 자원을 제거하였습니다.
errorException(true);
// 자원을 할당하였습니다.
// 에러가 발생했습니다.
// 자원을 제거하였습니다.

3.Class

  • 클래스(Class)
    👉 클래스는 정보를 묶는 것입니다!
    • 현실과 비슷한 개념(객체)을 나타내기 위한 도구
    • 클래스는 미리 정의해놓으면 필요할 때마다 해당 클래스로 동일한 틀을 가진 객체를 만들 수 있다.
      • 여기서 동일한 클래스를 이용해 생성한 객체를 인스턴스(Instance)라고 부른다.
class User { 
}

const user = new User();
user.name = "이용우";
user.age = 28;
user.tech = "Node.js";

console.log(user.name); // 이용우
console.log(user.age); // 28
console.log(user.tech); // Node.js

  • 생성자(Constructor)
    • “클래스 내부에서 constructor()로 정의한 메서드를 "생성자"
    • 미리 정의한 클래스를 기반으로 인스턴스를 생성할 때 Javascript 내부에서 호출되는 메서드
class User {
  constructor(name, age, tech) { // User 클래스의 생성자
    this.name = name;
    this.age = age;
    this.tech = tech;
  }
}

const user = new User("이용우", 28, "Node.js"); // user 인스턴스 생성

console.log(user.name); // 이용우
console.log(user.age); // 28
console.log(user.tech); // Node.js

  • this와 프로퍼티(Property)
    • 바꾸고 싶은 건 빵틀의 값이 아니라 실제 빵의 값
    • this 라고 표시함으로써, 빵틀 전체의 값을 바꾸는게 아니라 빵 하나의 값만 바꾸는 것
class User {
  constructor(name, age, tech) { // User 클래스의 생성자
    this.name = name;
    this.age = age;
    this.tech = tech;
  }
}

const user = new User("이용우", "28", "Node.js"); // user 인스턴스 생성
console.log(user.name); // 이용우
console.log(user.age); // 28
console.log(user.tech); // Node.js

생성자의 바디에서 this 키워드를 사용한다. 이 this는 클래스를 사용해 만들어 질 객체 자신을 의미하고 this 뒤에 붙는 name, age, tech는 클래스를 이용해서 만들어질 객체의 속성(Propety)이다.

  • 메서드(Method)
    • 프로퍼티 값이 함수일 경우에는 일반 함수와 구분하기 위해 메서드(Method) 라고 부른다. 즉, 메서드는 객체(Object) 에 묶여 있는 함수를 의미
class User {
  constructor(name, age, tech) { // User 클래스의 생성자
    this.name = name;
    this.age = age;
    this.tech = tech;
  }

  getName() { return this.name; } // getName 메서드
  getAge() { return this.age; }.  // getAge 메서드
  getTech() { return this.tech; } // getTech 메서드
}

const user = new User("이용우", "28", "Node.js"); // user 인스턴스 생성
console.log(user.getName()); // 이용우
console.log(user.getAge()); // 28
console.log(user.getTech()); // Node.js

Class라는 객체(Object)에 묶여있는 함수를 메서드(Method) 라고 부른다.

  • 상속이란?
    • 일반적으로 클래스의 인스턴스는 선언한 클래스의 기능을 모두 상속
    • 상속을 이용해 부모 클래스자식 클래스로 나뉘는데 부모 클래스의 경우 메서드, 내부 변수와 같은 정보를 자식 클래스에게 할당해줄 수 있다.
class User { // User 부모 클래스
  constructor(name, age, tech) { // 부모 클래스 생성자
    this.name = name;
    this.age = age;
    this.tech = tech;
  }
  getTech(){ return this.tech; } // 부모 클래스 getTech 메서드
}

class Employee extends User{ // Employee 자식 클래스
  constructor(name, age, tech) { // 자식 클래스 생성자
    super(name, age, tech);
  }
}

const employee = new Employee("이용우", "28", "Node.js");
console.log(employee.name); // 이용우
console.log(employee.age); // 28
console.log(employee.getTech()); // 부모 클래스의 getTech 메서드 호출: Node.js

User 클래스를 정의하고, Employee라는 이름의 새로운 클래스가 User를 상속한다. 생성자 내부의 super()는 생성자 내에서만, 그리고 this 키워드를 사용하기 전에만 쓸 수 있습니다

  • EmployeeUser의 서브 클래스로 정의
  • User의 자식 클래스인 Employee에서 User.getTech() 메서드를 호출
  • super
    • super 키워드는 함수처럼 호출할 수도 있고, this와 같이 식별자처럼 참조할 수 있는 키워드
      -super 키워드를 호출하면 부모 클래스생성자(constructor)를 호출
    • super 키워드를 참조하면 부모 클래스메서드(Method)를 호출할 수 있다.

profile
https://github.com/jennaaaaaaaaa

0개의 댓글