티스토리 뷰
객체 정의
key: name, age, type, weight
const dog = {
name: "슈슈",
age: 14,
type: "슈나우저",
weight: 7.2
};
console.log(dog);
console.log(dog.name);
console.log(dog.age);
const iron_man = {
name: "토니 스타크",
actor: "로버트 다우니 주니어",
alias: "아이언맨"
};
const captain_america = {
name: "스티브 로저스",
actor: "크리스 에반스",
alias: "캡틴 아메리카"
};
function print(hero) {
const text = `${hero.alias}(${hero.name}) 역할 받은 배우는 ${hero.actor}`;
console.log(text);
}
print(iron_man);
print(captain_america);
비구조화 할당 (객체 구조분해)
객체 내부의 필드를 밖으로 빼낸다.
즉 위의 코드의 hero.name, hero.alias 와 같이 hero. 을 없애서 정의 할 수있다.
코드를 더 간결하게 나타낼 수 있다.
function print(hero) {
const { alias, name, actor } = hero;
const text = `${alias}(${name}) 역할 받은 배우는 ${actor}`;
console.log(text);
}
print(iron_man);
print(captain_america);
바로 위의 코드에서는 파라미터를 hero 라고 정의했는데
const 를 만들 필요없이 바로 필드의 묶음으로 파라미터에서 정의할 수 있다.
const iron_man = {
name: "토니 스타크",
actor: "로버트 다우니 주니어",
alias: "아이언맨"
};
const captain_america = {
name: "스티브 로저스",
actor: "크리스 에반스",
alias: "캡틴 아메리카"
};
function print({ alias, name, actor }) {
const text = `${alias}(${name}) 역할 받은 배우는 ${actor}`;
console.log(text);
}
print(iron_man);
print(captain_america);
비구조화 할당 또 다른 사용 - 일부필드만을 불러올 수 있다.
const iron_man = {
name: "토니 스타크",
actor: "로버트 다우니 주니어",
alias: "아이언맨"
};
const { name } = iron_man;
console.log(name); // 토니스타크
객체 내에서 함수 정의
regular-expression (function) 에서
this 가 가리키는 대상은 현재 속해있는 객체 dog를 가리킨다.
그리고 다양하게 함수를 정의할 수 있다.
const dog = {
name: "개",
sound: "멍멍",
say() {
console.log(this.sound);
},
say1: function () {
console.log(this.sound);
},
say2: function say2() {
console.log(this.sound);
}
};
dog.say();
반면 arrow-expression에서는 this 가 가리키는 대상은 속해있는 객체 dog가 아니다.
this 를 출력해보면 undefined 가 출력되어있다.
arrow-expression에서 this가 가리키는 대상에는 sound라는 필드가 존재하지 않으며
콘솔에 Cannot read property 'sound' of undefined 라는 에러메시지가 출력된다.
const dog = {
name: "개",
sound: "멍멍",
say: () => {
console.log(this); // undefined
console.log(this.sound); // 에러발생
}
};
dog.say();
const dog = {
name: "개",
sound: "멍멍",
say() {
console.log(this.sound); // this - 함수가 위치한 객체를 가리킨다.(dog)
},
say1: function () {
console.log(this.sound);
},
say2: function say2() {
console.log(this.sound);
}
};
const cat = {
name: "고양이",
sound: "야용"
};
cat.say = dog.say;
dog.say(); //멍멍
cat.say(); //야옹
// 여기서 this는 undefined를 가리킨다.
const catSay = cat.say;
catSay(); // 에러발생
[ 참고 ] difference between regular-expression and arrow-expression
getter 와 setter
1. getter
- get 함수명() 형식
- 리턴값이 무조건 정의해야함.
- 필드를 불러올때 getter을 정의했다면, 객체.getter함수명 로 해당 필드의 값을 불러올 수 있다.
const numbers = {
a: 1,
b: 2,
get sum() {
console.log("sum 함수 실행");
//무조건 반환
return this.a + this.b;
}
};
numbers.a = 5;
console.log(numbers); // {a: 5, b: 2, sum: 7}
console.log(numbers.sum); // 7
numbers.b = 5; // {a: 5, b: 5, sum: 10}
console.log(numbers.sum); // 10
2. setter
- set 함수명(param) 형식
- 필드에 해당하는 값이 수정. (regular : this.필드명 = param)
- 객체.setter함수명 으로 해당필드에 대한 값을 세팅가능
const dog = {
_name: "멍멍이",
get name() {
console.log("_name 을 조회합니다 : ");
return this._name;
},
set name(name) {
this._name = name;
console.log(`이름이 변경됩니다 ${name}`);
}
};
console.log(dog.name); // getter name을 호출 : 멍멍이
dog.name = "뭉뭉이"; // setter name을 호출 : 멍멍이 -> 뭉뭉이로 수정.
console.log(dog._name); // 직접 필드값을 호출 : 뭉뭉이
console.log(dog.name); // getter name을 호출 : 뭉뭉이
3. getter & setter
const numbers = {
_a: 1,
_b: 2,
get a() {
return this._a;
},
get b() {
return this._b;
},
set a(v_a) {
this._a = v_a;
},
set b(v_b) {
this._b = v_b;
},
get sum() {
return this._a + this._b;
}
};
console.log("a: " + numbers.a); //get a: 1
console.log("b: " + numbers.b); //get b: 2
console.log(numbers.sum); //get sum: 3
numbers.a = 5; // set a
console.log("a: " + numbers.a); //get a: 5
console.log("b: " + numbers.b); //get b: 2
console.log(numbers.sum); //get sum: 7
numbers.b = 7; // set b
console.log("a: " + numbers.a); // get a: 5
console.log("b: " + numbers.b); // get b: 7
console.log(numbers.sum); //get sum: 12
화살표함수를 사용할 때 주의사항
- 화살표함수는 Lexical this 를 지원하므로 콜백함수로 사용하기 편하다.
- 화살표 함수는 생성자 함수로 사용할 수 없다.
- 화살표 함수로 객체의 메소드 정의할 때 문제가 발생한다. 그러므로 일반함수로 메소드를 정의한다.
https://poiemaweb.com/es6-arrow-function
'Backend > Typescript & Angular' 카테고리의 다른 글
splice & slice (0) | 2021.08.27 |
---|---|
배열 내장함수 - forEach/ map/indexOf/find/findIndex (1) | 2021.08.25 |
array & 반복문(for ... of, for ... in) (0) | 2021.08.24 |
함수 (0) | 2021.08.22 |
[시작] let/const & babel & null/undefined & 연산자 (0) | 2021.08.21 |
- Total
- Today
- Yesterday
- MongoDB
- nestjs
- 클린아키텍쳐
- OS
- 개발용어
- TDD
- 참고
- 갓생살자
- 바이트디그리
- git
- Mongoose
- 나도 할 수 있다
- 미완
- Jekyll
- TypeScript
- MySQL
- RDBMS
- 한달독서
- nestjs jest
- jest
- 한달어스
- typeORM
- IT용어
- 디지털디톡스
- 습관개선
- node.js
- Nest.js
- 스마트폰중독
- vscode
- gem
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |