자바스크립트를 사용하면서, this에 대해서 잘 알고 있다고 생각했는데 혼자만의 착각이였음을 오늘 느꼈다...😂
여러가지 상황에서 this를 사용하면서 this의 동작에 대해서 자세하게 알아본다 (node.js)
console.log(this);
let test = function () {
console.log(this);
}
let test = function() {
console.log(this);
}
let rst = test.bind(123);
console.log(rst); // bound test로 bind로 만들어진 함수를 의미
test(); // 기존의 일반함수의 this는 여전히 undefined
rst(); // 바인드 함수는 123을 this로 갖는다.
let Obj = {};
Obj.func = function() {
console.log(this);
}
Obj.func();
class Obj {};
let obj = new Obj();
obj.func = function() {
console.log(this);
};
obj.func();
const test = function() {
console.log(this);
}
const obj = {};
obj.test = test;
obj.test();
const test = function() {
console.log(this);
}.bind(100);
test.apply(200);
test.call(300);
let rst = test.bind(400);
rst();
const test = () => {
console.log(this);
};
let rst = test.bind(100);
rst();
//--------같은 결과--------//
const test = (() => {
console.log(this);
}).bind(100);
test();
const test = () => {
console.log(this);
}
const Obj = {};
Obj.func = test;
Obj.func();
상위 스코프의 this가 undefined이기 때문에 객체 내부에 있는 arrow function의 this도 undefined가 된다.
const outFunc = function () {
//outFunc's this
console.log("out", this);
const test = () => {
//testFunc's this
console.log("test", this);
};
const Obj = {};
Obj.func = test;
Obj.func();
}.bind(1234);
outFunc();
outFunc를 실행하면 bind를 통해 this가 1234로 변경되어 1234가 출력되고, test 함수가 outFunc 내부 객체인 obj의 속성으로 추가된 다음 실행한다. 그럴 경우 test 함수는 상위 스코프의 this인 1234를 출력한다.
Arrow function 의 this는 상위 스코프에 의해 결정된다.
const test = function () {
return () => console.log(this);
}.call("ABC");
(function () {
let arrow = () => console.log(this);
let obj = { arrow, test };
obj.arrow();
obj.test();
}.call("DEF"));
이 코드를 실행하면? test 함수는 실행하면 test함수의 this를 리턴한다. 이때 this는 call에 의해 ABC가 된다. test 함수는 일반 함수이기 때문에 bind, call, apply를 사용할 수 있다.
두 번째 즉시 실행 함수를 실행하면, arrow는 arrow function으로 this를 출력한다. 이때 call에 의해 this는 DEF가 된다. 즉시 실행 함수는 일반 함수이기 때문에 bind, call, apply를 사용할 수 있다. 그리고 obj 객체에 arrow, test 함수를 담는다. obj.arrow()를 실행하면 DEF
가 출력되고 obj.test() 를 실행하면 ABC
를 출력한다.
참고: 코드깎는노인 유튜브
Arrow function을 사용할 때, this 사용에 주의를 해야하고, 일반 함수에서는 bind를 통해 this 값을 변경할 수 있으니 대충 넘겨서는 안되겠다. 그리고 클래스로 객체를 만들 경우 반드시 new 키워드를 사용하자
this를 사용하는 법에 대해서 상세하게 정리를 해보려 했으나 아직도 부족한게 많다는 생각이든다... 클로저, 스코프, IIFE등 오늘 정리하려고 마음먹은 내용들은 많았지만 오늘은 this 밖에 못했다... 주말에 꼭 다 끝내야지.