-
[JS] ThisJavaScript 2021. 3. 21. 20:11728x90
- this는 크게 4가지 정도의 방법으로 사용됨
- this가 쓰이는 함수를 어떤 방식으로 실행하느냐에 따라서 그 역할이 구별됨
1. 기본 바인딩 (전역 객체)
- javascript 실행 환경의 전역 객체 (브라우저는 window 객체)
- this가 전역 객체를 context 객체로 갖음
- 전역 스코프에서 정의한 변수는 전역 객체에 등록됨
this.test1 = 'Test1'; console.log(this.test1) // 'Test1' const doSomething = () => { this.test2 = 'Test2'; } console.log(this.test1); // 'Test1' console.log(this.test2); // undefined doSomething(); console.log(this.test1); // 'Test1' console.log(this.test2); // 'Test2'
2. 암시적 바인딩
- 객체를 통해 함수가 호출된다면 그 객체가 this의 context 객체
function foo() { console.log(this.bar); } const obj = { bar: 'Test', func1: foo, func2: function() { console.log(this.bar); } } obj.func1(); obj.func2();
3. 명시적 바인딩
- 함수 객체는 call, apply, bind 메소드를 갖고 있는데 첫번째 인자로 넘겨주는 것이 this의 context 객체
function foo() { console.log(this); } const obj = { bar: 'Bar' }; foo.call(obj); // { bar: 'Bar' } foo.call('Test'); // String {"Test"}
4. new 바인딩
- 동작 순서
- 객체 생성
- 생성된 객체의 Prototype 체인이 호출 함수의 프로토타입과 연결됨
- 1에서 생성된 객체를 this의 context 객체로 사용하여 함수가 실행됨
- 함수가 객체를 반환하지 않는 한 1에서 생성된 객체가 반환됨
function foo(val) { this.val = val; } const bar = new foo('test'); console.log(bar.val);
728x90'JavaScript' 카테고리의 다른 글
[Javascript] 렉시컬 환경, 클로저 (0) 2023.09.17 Mac에서 yarn global 설치후 command not found 해결 방법 (0) 2021.01.31 [JS] 접근자 프로퍼티(Accessor Property) (0) 2020.12.24 [JS] 브라우저 타임존 가져오는 방법 (0) 2020.12.23 [JS] 객체 배열 정렬 (0) 2020.11.30