JavaScript 예약어
자기 참조 변수(self-reference variable)
보통 객체의 메서드 내부 또는 생성자 함수 내부에서 쓰인다
브라우저 환경으로 한정하여 정리한 내용입니다.
nods.js 환경 등 다른 환경에서는 또 다른 일들이 벌어집니다!
this;
window
전역 객체를 참조한다.
function fn() {
console.log(this);
}
fn(); // window
window
전역 객체를 참조한다.
'use strict';
function fn() {
console.log(this);
}
fn(); // undefined
undefined
const foo = {
name: 'cat',
callName: () => console.log(this),// window
}
화살표 함수의 this
는 상위 환경의 this
를 참조한다.
위와 같은 경우는 상위 환경이 전역이기 때문에 전역 객체를 가리키게 된 것이다.
const button = document.querySelector(".btn");
button.addEventListener("click", () => {
console.log(this); // window
});
콜백 함수가 화살표 함수로 작성되어 this
가 전역 객체 window
를 가리킨다.
const obj = {
fn: function() {
console.log("this", this);
}
}
obj.fn(); // obj
객체의 메서드를 호출할 때 this
를 내부적으로 바꿔준다.
const obj = {
fn: function() {
console.log("this", this);
}
}
obj.fn(); // obj
const fn2 = obj.fn;
fn2(); // window
fn2()
의 결과가 obj
가 아닌 이유는 fn2
이라는 변수에 obj.fn
을 값으로 할당했기 때문에 obj
의 메서드가 아닌 그냥 함수이다.
함수 안에서 사용하는 this
는 window
를 가리키기 때문에 fn2
도 window
를 가리킨다.
bind()
메소드는 func.bind(thisArg[, arg1[, arg2[, ...]]])
의 형태로 사용한다.func
에 this
를 thisArg
로 전달하여 원본 함수의 복제본을 반환한다.const obj = {
name: "cat",
}
function func() {
console.log("func의 this" , this);
};
// func 함수의 this 를 obj 로 전달한 함수를 funcUser라는 변수에 할당
let funcUser = func.bind(obj);
funcUser(); // obj
call()
메소드는 func.call(thisArg[, arg1[, arg2[, ...]]])
의 형태로 사용한다.func
라는 함수의 this
를 누구로 변경할 건지 설정할 수 있다.func.call(객체, 인자값);
const obj1 = {
name: "cat",
func : function() {
console.log("name은", this.name);
console.log(this);
}
}
obj1.func(); // name은 cat
const obj2 = {
name: "dog",
func : function() {
console.log("좋아하는 동물은", this.name);
}
}
obj2.func(); // 좋아하는 동물은 dog
obj1.func.call(obj2); // name은 dog
apply()
메서드는 func.call(thisArg[, arg1[, arg2[, ...]]])
의 형태로 사용한다.call()
메서드와 비슷한데 인자값만 다르다.func.call(객체, 인자값 배열);
function get(a, b) {
console.log(a + b + arguments[2]);
}
get.apply(this, [10, 20, 30]); // 60
var obj = {
value: 123,
nestedObj: {
value: 456,
get: function (a, b) {
console.log(a + " " + b + " " + this.value + " " + arguments[2]);
},
},
};
obj.nestedObj.get.apply(obj, [1, 2, 3]); // 1 2 123 3
obj.nestedObj.get.apply(obj.nestedObj, [1, 2, 3]); // 1 2 456 3
혹시나 잘못된 정보가 있다면 댓글로 알려주세요 ! 저의 성장의 큰 도움이 될 것 같습니다.🌱
🙋♂️ 브라우저 환경이 아닌 node.js 환경이라면 window 전역 객체를 참조하지 않고 global 객체를 참조할 것 같아요.
도입부에 브라우저 환경에서의 내용이라는걸 명시해주면 더 좋을 것 같습니다 👍