Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- PostgreSQL
- 개발자
- SSE
- mariadb
- Lag
- node.js
- 실시간알림
- EventSource
- ServerSentEvent
- Node.js기본
- partitioning
- 성장기
- localStorage
- node.js란
- 열공하자
- 파티셔닝
- Partition
- frontend
Archives
- Today
- Total
써치킴의 우당탕탕 개발 블로그
[JS Essentials][Ch2][클래스] this 본문
this
- 일반(Normal) 함수는 호출 위치에 따라 this 정의
- 화살표(Arrow) 함수는 자신이 선언된 함수에서 함수 범위에서 this 정의
const searchkim = {
name : 'SearchKim',
normal : function () { // 익명의 일반함수
console.log(this.name);
},
arrow : () => { // 화살표 함수
console.log(this.name);
}
}
// () : 호출
// 일반함수는 searchkim이라는 객체가 this이기 때문에 this의 name이 콘솔에 표출
searchkim.normal(); // 객체의 메소드 실행
// undefined 표출
searchkim.arrow(); // 객체의 메소드 실행
const amy = {
name : 'Amy',
// searchkim 객체의 normal 데이터 -> 즉, normal의 일반함수 자체가 amy의 normal에 할당
normal : searchkim.normal,
// searchkim 객체의 arrow 데이터 -> 즉, arrow의 화살표함수 자체가 amy의 arrow에 할당
arrow : searchkim.arrow
}
amy.normal();
amy.arrow();
function User(name) { // 생성자 함수
this.name = name;
}
User.prototype.normal = function () { // 메소드(일반 함수 할당)
console.log(this.name);
}
User.prototype.arrow = () => { // 메소드(화살표 함수 할당)
console.log(this.name);
}
// 생성자 함수를 실행한 객체 데이터(search)
const search = new User('SearchKim');
search.normal(); // SearchKim 표출
// 자신이 선언된 함수에서 this가 정의되기 때문에 화살표 함수 내(범위)에 참조할 name이 보이지 않음
search.arrow(); // undefined 표출
const timer = {
name : 'Searchkim',
timeout : function () {
// setTimeout(함수, 시간)
// 자신이 선언된 함수 범위에 name이 있기 때문에 콘솔에 정상적으로 표출됨
setTimeout(() => {
console.log(this.name);
} , 2000);
}
}
timer.timeout();
따라서 setTimeout, setIntervel은 화살표 함수를 사용하는 것을 권장한다!
'파도파도 나오는 JavaScript' 카테고리의 다른 글
[JS Essentials][Ch2][클래스] 상속(확장) (0) | 2022.01.28 |
---|---|
[JS Essentials][Ch2][클래스] ES6 Classes (0) | 2022.01.28 |
[JS Essentials][Ch2][클래스] 생성자 함수(prototype) (0) | 2022.01.28 |
[JS Essentials][Ch2][함수] 콜백 (Callback) (0) | 2022.01.28 |
[JS Essentials][Ch2][함수] 타이머 함수 (0) | 2022.01.28 |
Comments