javaScript [this]

Soozynn·2021년 8월 11일
0

JavaScript

목록 보기
2/6

함수명 앞에 function 대신 class = 'use strict'?
에로우 함수일때 디스는
4가지의 기준
중첩된 함수에서 상위 스코프의 기준

⛔ A common trap with the function invocation is thinking that this is the same in an inner function as in the outer function.
기능 호출과 함께 일반적인 트랩(함정)은 내부 기능에서도 외부 기능에서와 동일하다고 생각하는 것입니다

✅The context of the inner function (except arrow function) depends only on its own invocation type, but not on the outer function’s context.
내부 함수의 컨텍스트(화살표 함수 제외)는 외부 함수의 컨텍스트가 아닌 자체 호출 유형에 따라 달라집니다.

const numbers = {
  numberA: 5,
  numberB: 10,

  sum: function() { // => 처음 sum이 호출된 방식(객체메소드)은 dot nocation 방식으로 this가 numvers에 바인딩
    console.log(this === numbers); // => true

    function calculate() {
      // this is window or undefined in strict mode
      console.log(this === numbers); // => false
      return this.numberA + this.numberB; // 전역객체에서  numberA + numberB 값을 찾을 수 없다
    }

    return calculate(); // => 내부 함수 calculate의 호출 방식 주목(일밤함수)
  }
};

numbers.sum(); // => NaN or throws TypeError in strict mode, 따라서 NaN
//(TypeError: Cannot read property 'numberA' of undefined 엄격 모드에서는 오류가 발생)

위에 코드에서
calculate를 호출한 방식은 일반 함수 호출 방식이다
따라서 calculate()의 this는 Global object or windowundefined 출력
외부 함수 numbers.sum()가 컨텍스트를 numbers 객체 자체로 로 가지고 있더라도 내부함수 calculate를에는 영향을 미치지 않는다.
고로 5 + 15 값은 절대 나오지않는다

⛔'use strict' 엄격모드⛔

엄격 모드는 현재 범위뿐만 아니라 내부 범위(내부에 선언된 모든 함수에 대해)에서도 활성화됩니다.

https://github.com/lydiahallie/javascript-questions/blob/master/ko-KR/README-ko_KR.md
https://dmitripavlutin.com/gentle-explanation-of-this-in-javascript/
https://dev.to/liaowow/take-this-quiz-understand-how-this-works-in-javascript-44dj
https://bluayer.com/25

0개의 댓글