중괄호 {}
내에 0개 이상의 프로퍼티를 정의해서 선언let objectLiteral = {
key: 'Value',
helloWorld: function () {
return "Hello world";
}
};
const human = {
// 프로퍼티 키: 'name', 프로퍼티 값: '이용우'
name: '이용우',
// 프로퍼티 키: 'human age', 프로퍼티 값: 28
'human age': 28
}
let objectLiteral = {
key: 'Value', // 프로퍼티
helloWorld: function () { // 메서드
return "Hello world";
}
};
console.log(objectLiteral.helloWorld()); // Hello world
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
를 호출하면 그 즉시 현재 실행되고 있는 함수는 실행을 멈춤.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
try
에서는 특정한 ‘자원’을 가지고 처리할 때가 있다. 하지만 무의미한 메모리를 차지하게 될 것 이므로 에러 여부와 상관없이 일정 시점에서는 해당 ‘자원'을 삭제 시켜야한다.finally
는 에러가 발생했는지 여부와 상관없이 언제든지 실행됩니다.function errorException(isThrow) {
try {
console.log('자원을 할당하였습니다.');
if (isThrow) throw new Error();
} catch (error) {
console.log('에러가 발생했습니다.');
} finally {
console.log('자원을 제거하였습니다.');
}
}
errorException(false);
// 자원을 할당하였습니다.
// 자원을 제거하였습니다.
errorException(true);
// 자원을 할당하였습니다.
// 에러가 발생했습니다.
// 자원을 제거하였습니다.
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()
로 정의한 메서드를 "생성자"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
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)이다.
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 키워드를 사용하기 전에만 쓸 수 있습니다
User.getTech()
메서드를 호출super
키워드는 함수처럼 호출할 수도 있고, this
와 같이 식별자처럼 참조할 수 있는 키워드super
키워드를 호출하면 부모 클래스의 생성자(constructor)를 호출super
키워드를 참조하면 부모 클래스의 메서드(Method)를 호출할 수 있다.