반응형
Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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
Archives
Today
Total
관리 메뉴

웹풀스택 공부 중

JavaScript의 기본 - 2 본문

웹개발/JavaScript

JavaScript의 기본 - 2

lukeit 2024. 9. 10. 10:49

This

This는 두 가지로 나뉩니다:

  • 일반 함수 표현식 내 this: 객체 동적 바인딩 = 동적 스코프 (Dynamic Scope)
    • 일반 함수: 그냥 global 객체
    • 메서드: 객체화 혹은 초기화 여부에 따라 해당 객체 내 스코프가 결정됨
    • function Constructor1() { // 호출지 : Constructor1 객체 this.field = 0; // (위와 동일) Constructor1 객체 내 this.field = 0 console.log(this.field); // (위와 동일) Constructor1 객체 내 this.field = 0 function doublewrapper() { // 호출지 : 전역객체 (객체화 혹은 초기화 되지 않음) this.field = 1; // (위와 동일) 전역객체 내 this.field = 1 console.log(this.field); // (위와 동일) 전역객체 내 this.field = 1 function Constructor2() { // 호출지 : Constructor2 객체 console.log(this.field); // (위와 동일) Constructor2 객체 내 this.field = undefined } new Constructor2(); } doublewrapper(); } new Constructor1(); console.log(field); // 전역객체 내 this.field = 1
```
function Constructor1() {               // 호출지 : Constructor1 객체
    this.field = 0;                     // (위와 동일) Constructor1 객체 내 this.field = 0
    console.log(this.field)             // (위와 동일) Constructor1 객체 내 this.field = 0
    function doublewrapper() {          // 호출지 : 전역객체 (객체화 혹은 초기화 되지 않음)
        this.field = 1;                 // (위와 동일) 전역객체 내 this.field = 1
        console.log(this.field);        // (위와 동일) 전역객체 내 this.field = 1

        function Constructor2(){        // 호출지 : Constructor2 객체
            console.log(this.field)     // (위와 동일) Constructor2 객체 내 this.field = undefined
        }
        new Constructor2()
    }
    doublewrapper()
}
new Constructor1();
console.log(field);                     // 전역객체 내 this.field = 1



// Constructor의 this.field는 함수내 변수
// doublewrapper의 this.field는 글로별 변수이다 (new를 사용하지 않았기 때문에)
```
-   `Constructor`의 `this.field`는 함수 내 변수
-   `doublewrapper`의 `this.field`는 전역 변수 (new를 사용하지 않았기 때문)
  • 화살표 함수 표현식 내:
    • 정적 바인딩 = 정적 스코프 (Static, Lexical Scope)

명시적 바인딩 (Explicit Binding)

  • 명시적 바인딩이란 해당 함수가 어떤 객체에서 호출되었는지의 기준을 직접 설정하는 것
    • call, apply, bind를 통해 이루어짐
      • a1.call(object): 바인딩만 수행
      • a1.bind(object)(): 바인딩 및 호출
function createObject() {
// this.foo = 21 <- 이게 call로 만들어진것 (함수 내 Global)
  console.log('Inside `createObject`:', this.foo)
  return {
    foo: 42,
    bar: () => console.log('Inside `bar`:', this.foo),
  };
}
createObject.call({ foo: 21 }).bar()
// call <- 객체화 후 foo의 값을 함수 내 Global로 넣어준다
// bar은 그럼이제 정적 바인딩이 된다
// 그래서 42가 아닌 21이 나온다

 

 

 

---

쓸때마다 티스토리 글 포멧이 계속 바뀐다... 짜증난다..

반응형

'웹개발 > JavaScript' 카테고리의 다른 글

13 - 1. JavaScript 심화 문법  (2) 2024.10.10
10 - 2. Module System  (4) 2024.10.10
10 - 1. JS 객체 정의 및 사용  (2) 2024.10.08
JavaScript의 기본  (0) 2024.09.03