상수/변수 선언
- var 대신에 const 혹은 let을 이용한다.
- const는 블록 범위의 상수를 선언하며, 상수의 값은 재할당할 수 없다.
const number = 42;
try {
number = 99;
} catch (err) {
console.log(err);
// expected output: TypeError: invalid assignment to const `number'
// Note - error messages will vary depending on browser
}
console.log(number);
// expected output: 42
- let은 블록 스코프의 범위를 가지는 지역 변수를 선언하며, 선언과 동시에 임의의 값으로 초기화할 수 있다.
let x = 1;
if (x === 1) {
let x = 2;
console.log(x);
// expected output: 2
}
console.log(x);
// expected output: 1
Object
- JS에서 객체는 속성의 컬렉션으로, 속성은 키와 값 사이의 연결 관계이다.
- 만약 속성의 값이 함수인 경우에 메서드라고 부른다.
let name = "Kim";
let age = 20;
let person = {
name, // 단축 속성명
age,
print() {
console.log(`name: ${this.name}, age: ${this.age}`); // person.print()로 사용 가능
}
};
객체 복사
- JS는 Object와 Array에 대해서는 대입 시 얕은 복사가 이루어진다.
const obj1 = { value: 10 };
const obj2 = obj1; // 얕은 복사
obj1.value1 += 1;
console.log(`obj1:`, obj1);
console.log(`obj2:`, obj2);
- 깊은 복사를 하려면 JSON으로 직렬화한 뒤 다시 객체로 역직렬화시킨다.
const obj3 = JSON.parse(JSON.stringify(obj1))
구조 분해 할당
- 구조 분해 할당은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 해주는 JS의 표현식이다.
var a, b, rest;
[a, b] = [10, 20];
console.log(a); // 10
console.log(b); // 20
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a); // 10
console.log(b); // 20
console.log(rest); // [30, 40, 50]
({ a, b } = { a: 10, b: 20 });
console.log(a); // 10
console.log(b); // 20
// Stage 4(finished) proposal
({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
console.log(a); // 10
console.log(b); // 20
console.log(rest); // {c: 30, d: 40}
배열 구조 분해
- 순서를 기준으로 할당되며, 할당될 값이 없으면 undefined
let [name] = ["Kim", 20, "Seoul"];
let [,age,] = ["Kim", 20, "Seoul"];
let [name, age, region, height] = ["Kim", 20, "Seoul"] // height는 undefined
let [name, age, region, height=150] = ["Kim", 20, "Seoul"] // default값 설정
객체 구조 분해
const person = {
name: "Kim",
age: 20,
region: "Seoul"
};
const {age, name, height} = person;
const people = [
{ name: 'Lee', age: 10, region: 'Seoul' },
{ name: 'Kim', age: 20, region: 'Pusan' }
];
for (const {name, age} of people) {
console.log(name, age);
}
const print_person = ({ name, age }) => {
console.log(name);
};
print_person(person);
깊은 값 비구조화 할당
const person = {
name: 'Kim',
age: 20,
region: {
country: '서울',
postcode: '06222',
}
};
const { name, region: { postcode }} = person; // 이때 region은 실제로 값이 할당되지 않는다.
console.log(name, postcode);
전개 구문
- 배열이나 문자열과 같이 반복 가능한 문자를 0개 이상의 인수 또는 요소로 확장할 수 있다.
let [name, ...rest] = ["Kim", 20, "Seoul"];
let names = ["Lee", "Park"];
let students = ["Kim", ...names];
let person1 = {
name: "Kim",
age: 20,
region: "Seoul"
};
let person2 = {
...person1,
name: "Lee" // 중복되는 속성명은 마지막 값으로 저장
};
함수
Named Parameters
function print_person({ name, age, region }) {
console.log(name, age, region)
}
print_person({ name: 'Kim', age: 20, region: 'Seoul' });
Arrow Function
- arrow function은 자신의 this가 없는 대신, arrow function을 둘러싸는 lexical scope의 this가 사용된다.
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // |this|는 Person 객체를 참조
}, 1000);
}
var p = new Person();
고차 함수
- 함수를 인자로 받거나 반환하는 것이 가능하며, 다른 함수를 조작할 수 있는 함수
const base_10 = fn => (x, y) => fn(x, y) + 10;
let mysum = (x, y) => x + y;
mysum = base_10(mysum);
console.log(mysum(1, 2));
상속
- 다른 언어와 마찬가지로 class와 extends를 사용할 수 있으며, constructor()를 지정할 수 있다.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
print() {
console.log(this.name + ", " + this.age);
}
}
const person = new Person("Kim", 20);
person.print();
class Developer extends Person {
constructor(name, age, field) {
super(name, age);
this.field = field;
}
print() {
super.print();
console.log(`field : ${this.field}`);
}
}
'Frontend' 카테고리의 다른 글
순수 함수와 커링 기법 (0) | 2022.03.17 |
---|---|
Promise와 async/await (0) | 2022.03.17 |
react-router-dom과 로그인 인증 (0) | 2022.01.22 |
백엔드 통합과 CORS (0) | 2022.01.20 |
이벤트 처리 (0) | 2022.01.20 |