this의 값은 함수를 호출하는 방법에 의해 결정된다.
호출한 놈 (객체) ===
this
this
는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수이다.
자바스크립트의 경우 함수 호출 방식에 의해 this
에 바인딩할 어떤 객체가 동적으로 결정된다. 다시 말해, 함수를 선언할 때 this에 바인딩할 객체가 정적으로 결정되는 것이 아니고, 함수를 호출할 때 함수가 어떻게 호출되었는지에 따라 this에 바인딩할 객체가 동적으로 결정된다.
함수 내부에서의 this
값은 함수를 호출한 방법에 의해 좌우된다.
전역에 작성된 함수(엄격모드X)는 기본값으로 window 전역 객체
를 참조.
메소드의 내부함수일 경우에도 this는 전역객체에 바인딩된다.
콜백함수의 경우에도 this는 전역객체에 바인딩된다.
function func() {
return this;
}
// 브라우저
func() === window; // true
const func2 = () => {
return this;
}
// 브라우저
func2() === window; // true
// 메소드 내부함수일 경우에도 this는 전역객체에 바인딩된다.
var value = 1;
var obj = {
value: 100,
foo: function() {
console.log("foo's this: ", this); // obj
console.log("foo's this.value: ", this.value); // 100
function bar() {
console.log("bar's this: ", this); // window
console.log("bar's this.value: ", this.value); // 1
}
bar();
}
};
obj.foo();
// 콜백함수의 경우에도 this는 전역객체에 바인딩된다.
var value = 1;
var obj = {
value: 100,
foo: function() {
setTimeout(function() {
console.log("callback's this: ", this); // window
console.log("callback's this.value: ", this.value); // 1
}, 100);
}
};
obj.foo();
내부함수는 일반 함수, 메소드, 콜백함수 어디에서 선언되었든 관게없이 this는 전역객체를 바인딩한다.
함수를 어떤 객체의 메소드로 호출하면 this의 값은 그 객체를 사용한다.
const user = {
firstName: 'Tess',
lastName: 'Jang',
getFullName: function () {
return `${this.firstName} ${this.lastName}`;
},
};
new 키워드와 함께 생성자로 사용하면 this는 새로 생긴 객체에 묶인다.
// 생성자 함수
function Person(name) {
this.name = name;
}
var me = new Person('Lee');
console.log(me); // Person {name: "Lee"}
// new 연산자와 함께 생성자 함수를 호출하지 않으면 생성자 함수로 동작하지 않는다.
var you = Person('Kim');
console.log(you); // undefined
bind
: 호출 방법과 무관하게 고정시키려면 bind를 쓰면 된다. arrow function
: 화살표 함수에서 this는 자신을 감싼 정적 범위입니다.const someone = {
name: 'song',
whoAmI: function() {
console.log(this);
}
}
someone.whoAmI(); // someone 객체 뜸
let myWhoAmI = someone.whoAmI;
myWhoAmI(); // Window 객체 뜸
let bindWhoAmI = myWhoAmI.bind(someone);
bindWhoAmI(); // someone 객체 뜸 (bind)
let btn = document.getElementById('btn');
btn.addEventListner('click', bindWhoAmI); // someone 객체 (bind로 고정)
참고링크