TIL_210225
7989 단어 thisJavaScriptTILJavaScript
Today I Learned
- 클래스와 인스턴스
- this
- call, apply 메소드
- bind 메소드
- 구조분해 할당 - 단축문법
클래스와 인스턴스
- 클래스
- 연관되어 있는 변수(속성)와 메소드의 집합
- 객체를 만들어 내기 위한 일종의 설계도
class Car {
constuctor(brand, name, color) { // 생성자 함수
this.brand = brand; // this는 인스턴스 객체
this.name = name; // brand, name, color는 속성
this.color = color;
}
refuel() { // refuel, drive는 메소드
console.log('연료를 공급합니다')
}
drive() {
console.log('운전을 시작합니다')
}
}
- 인스턴스
- 클래스(설계도)를 바탕으로 new 키워드를 이용해 생성된 객체
- 생성자 함수에서 this의 값이 됨
let avante = new Car('hyundai', 'avante', 'black');
avante.color; // 'black'
avante.drive(); // '운전을 시작합니다'
this
- this는 함수 실행 시 호출 방법에 의해 결정되는 특별한 객체
- 함수 실행 시 결정되며, 함수가 실행되는 맥락(context)에 따라 this가 가리키는 대상이 달라진다.
- call, apply 메소드
- bind 메소드
- 연관되어 있는 변수(속성)와 메소드의 집합
- 객체를 만들어 내기 위한 일종의 설계도
class Car {
constuctor(brand, name, color) { // 생성자 함수
this.brand = brand; // this는 인스턴스 객체
this.name = name; // brand, name, color는 속성
this.color = color;
}
refuel() { // refuel, drive는 메소드
console.log('연료를 공급합니다')
}
drive() {
console.log('운전을 시작합니다')
}
}
- 클래스(설계도)를 바탕으로 new 키워드를 이용해 생성된 객체
- 생성자 함수에서 this의 값이 됨
let avante = new Car('hyundai', 'avante', 'black');
avante.color; // 'black'
avante.drive(); // '운전을 시작합니다'
함수 실행 방법에 따라 this가 어떻게 결정되는지 알아보자.
- Function 호출
foo()
// this는 window(브라우저) or global(Node.js)
// 앞에 아무것도 없는 메소드(함수)는 사실 그 앞에 window(또는 global)가 생략되어 있는 것. 즉, 원래 window.foo()
- Method 호출
obj.foo()
// this는 obj
- new 키워드를 이용한 생성자 호출 (OOP에서 주로 사용)
new Foo()
// this는 새롭게 생성된 인스턴스 객체
- .call 또는 .apply 호출
foo.call()
foo.apply()
// 첫번째 인자가 this가 됨
//////////// call, apply, bind 추가할 것 ///////////
구조분해 할당 - 단축문법
배열
let arr = [1,2,3,4,5]
let [a, b] = arr;
console.log(a); // 1
console.log(b); // 2
객체
const student = { name: '박해커', major: '물리학과' };
const { name } = student
const { major } = student
console.log(name) // '박해커'
console.log(major) // '물리학과'
- 화살표 함수에서 this 접근하면 상위 scope에서 값을 가져옴
✍️
this this this this슈탈트 붕괴현상... 하면 할수록 헷갈린다
더 공부할 것
Author And Source
이 문제에 관하여(TIL_210225), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@wpdbs4419/TIL210225저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)