- 일반 함수에서의 this : 함수를 호출한 객체
- arrow함수에서의 this : 함수를 감싸는 상위 스코프
//전역 this
console.log(this) // window{...}
//엄격모드에서의 this
function f1() {
"use strict";
return console.log(this);
}
f1(); // undefined
//일반 함수에서의 this
function f2() {
return console.log(this);
}
f2(); // window{...}
//객체 메서드에서의 this
const f3 = {
name : "test",
main : function(){
console.log(this)
}
}
f3.main(); // {name: 'test', main: ƒ} , 함수를 호출한 객체
//화살표함수의 this
const f4 = {
name : "test",
main : () => {
console.log(this);
}
}
f4.main(); // window{...}
Function.prototype.bind
- this값을 정적으로 지정하고 싶을 때
- 화살표함수는 ❌
function greet() {
console.log(this.name);
}
const person = { name: 'Alice' };
const greetPerson = greet.bind(person);
greetPerson(); // Alice
this - JavaScript | MDN
JavaScript에서 함수의 this 키워드는 다른 언어와 조금 다르게 동작합니다. 또한 엄격 모드와 비엄격 모드에서도 일부 차이가 있습니다.
developer.mozilla.org
'자바스크립트' 카테고리의 다른 글
[DeepDive]10~12장 객체 리터럴/원시 값과 객체의 비교/함수 (1) | 2024.10.21 |
---|---|
[DeepDive]7~9장 연산자/제어문/타입 변환과 단축평가 (1) | 2024.10.17 |
[JS]클로저(Closure) (0) | 2024.10.10 |
[JS]프로토타입 (2) | 2024.10.10 |
[JS]비동기(async/await) (0) | 2024.10.10 |