this 바인딩
JS의 this 키워드는 실행 컨텍스트를 참조해 여러가지 값을 가질 수 있다. 이는 this를 호출하는 함수의 환경에 따라 달라진다. 케이스별로 this 값의 변화를 알아보자.
- 전역 / 함수 스코프의 this: 전역 객체를 가리킴(window, global)
console.log(this); // 전역: window | global function someFunc() { console.log(this); // 일반 함수: window | global } someFunc();
- 화살표 함수의 this: 함수 자체의 this 바인딩은 없음. 함수를 둘러싼 가장 가까운 this의 값, 또는 전역 객체를 참조함(렉시컬 this)
const obj = { name: 'wavy', outerFunc: function () { const innerFunc = () => { console.log(this.name); }; innerFunc(); }, }; wavy.sayHello(); // 'wavy' const innerFunc = () => { console.log(this.name); // 'window' };
- 메서드 내 this: 메서드를 호출한 객체를 가리킴
const wavy = { name: 'wavy', sayHello: function () { console.log(this.name); }, }; wavy.sayHello(); // 'wavy'
- 생성자 함수 내 this: new✨️ 키워드를 이용해 생성한 인스턴스를 가리킴
function SomeClass() { this.name = 'wavy'; } const wavy = new SomeClass(); // new 키워드를 사용해 인스턴스 생성😀 console.log(wavy.name); // 'wavy'
- 명시적 바인딩(call, apply, bind)의 this: 직접 지정할 수 있음
메서드를 사용한 this 명시적 바인딩
화살표 함수는 this 바인딩 생성 불가하므로 예제는 함수 선언문을 통해 작성했다.
- call:
someFunc.call(this, firstArgue)
- apply:
someFunc.apply(this, \[firstArgue\])
call과 유사하지만 배열 형태의 인자를 받는 것이 차이 - bind:
const newFunc = someFunc.bind(this, firstArgue)
this 값이 고정된 새로운 함수를 반환함. 사용시 추가적인 호출 과정이 필요함.const wavy = { name: 'wavy' }; function someFunc(arg1, arg2) { console.log(`${arg1}, ${this.name}. ${arg2}`); } someFunc.call(wavy, 'Hello', 'See you'); // "Hello, wavy. See you" someFunc.apply(wavy, ['Hi', 'Goodbye']); // "Hi, wavy. Goodbye" const newFunc = someFunc.bind(wavy, 'Hey', 'Take care'); newFunc(); // "Hey, wavy. Take care"
'STORAGE > JavaScript|TypeScript' 카테고리의 다른 글
싱글톤 패턴 (0) | 2024.04.01 |
---|---|
동적으로 css 변수 만들기 (0) | 2023.09.25 |
tsconfig.json (0) | 2023.07.10 |
댓글