-
[JS] this 바인딩에대한 고찰... (항해 수료 후 근황, 스파르타 취업준비반)Java Script & Type Script/Trouble Shooting 2023. 4. 3. 14:01728x90
항해99를 수료하고,, 스파르타에서 하는 취업대비반에서 이것저것 도움 받으며 면접준비+이력서첨삭+코딩공부를 하고있다.
면접 예상질문을 받고 답변을 준비하며 거기에 대한 공부를 하는데, 항해를 하는동안은 집중적으로 실전에 필요한 부분만 빠르게 습득하고 적용시키느라 디테일한 것들을 많이 공부하지 못했다. 그래서 지금 하고있는 면접대비 답변정리가 실제로 면접에서도 도움이 되겠지만 무엇보다 전반적인 JS에대한 이해도를 높이고있는 것 같아 좋은 것 같다.
제일 어려웠던 this에 대해 좀 더 작성해보려한다!
this바인딩의 예시
-일반함수 호출시 this바인딩 (window객체가 출력됨.)
function myFunction() { console.log(this); } myFunction(); // this는 전역 객체를 참조
-메서드로 호출(객체의 속성으로 정의된 함수를 해당 객체의 메서드로서 호출)
const myObject = { myMethod() { console.log(this); } }; myObject.myMethod(); // this는 myObject를 참조
-생성자 함수로 객체를 생성할 때 this바인딩
function MyClass() { console.log(this); } const myInstance = new MyClass(); // this는 myInstance를 참조
-call,apply,bind메서드를 사용하여 this바인딩 (this를 강제로 지정하기!! )
function myFunction() { console.log(this); } const myObject = { name: 'John' }; myFunction.call(myObject); // this는 myObject를 참조 const myBoundFunction = myFunction.bind(myObject); myBoundFunction(); // this는 myObject를 참조
-화살표함수에서의 this바인딩
const myObject = { myMethod: () => { console.log(this); } }; myObject.myMethod(); // this는 함수가 선언된 곳의 바깥쪽 스코프를 참조
화살표함수에서 this는 함수가 선언된 곳의 바깥족 스코프에서 상속을 받는다.
일반함수에서는 함수가 호출되는 방식에 따라 this가 결정되는데, 화살표함수에서는 this가 바인딩 되지 않아 함수가 선언된 곳의 바깥쪽 스코프에서 this를 참조한다.
const person = { naem: "chaejung", greet: ()=> { console.log(`hi, my name is ${this.name}`) } }; person.greet() //"hi, my name is undefined"
킹받쥬 undefined가 뜨는 이유는 this가 선언된 곳 바깥쪽 스코프에서 상속받는 전역객체를 참조하기 때문.
이를 수정해 메서드를 호출할 때 this를 person으로 지정
const person = { name: "chaejung", greet: function () { console.log(`Hello, my name is ${this.name}`); }, }; person.greet();
일반함수일 때는 this가 속한 객체를 참조. bind메서드를 이용해 함수를 호출할 때 사용할 this값을 영구적으로 지정할 수 잇다.
새로운 함수를 반환해 이후에 호출할 때 this값이 항상 지정한 값으로 설정된다.
아래는 greet함수에 person객체를 this에 지정하는 함수로 바인딩하는 예시이다.
function greet(message) { console.log(`${message}, my name is ${this.name}`); } const person = { name: "chaejung" }; const greetPerson = greet.bind(person); greetPerson("Hello"); // "Hello, my name is chaejung"
위 예시에서는 greet함수에 person객체를 this에 지정하는 함수로 바인딩하고 greetperson이라는 새로운 함수를 반환한다.
greetperson함수를 호출하며 Hello를 인수로 전달하면 this값이 항상 person객체로 설정되므로 Hello, my name is chaejung이 출력됨.
728x90'Java Script & Type Script > Trouble Shooting' 카테고리의 다른 글
Storybook S3로 배포하기 (S3, cloudfront, route53) git actions 자동배포까지! (1) 2024.06.01 [Trouble Shooting] 맥에서만 발생하는 권한에러 [eslint] EACCES: permission denied, mkdir (1) 2023.12.24 38. 3월 16일 (0) 2023.03.16 34. react-datepicker 야무지게 잘 쓰는 법. Feat.datepicker 시차해결. datepicker한국시간표현 (0) 2023.03.04 30. Final Project [trouble shooting-3] - useState비동기문제 함수형 업데이트로 해결! chat GPT야 고마워 (0) 2023.02.23