This?
This 바인딩은 실행컨텍스트가 실행될때 결정된다.
실행컨텍스트는 함수가 호출할때 실행된다.
즉 호출하는 방식에 따라 This가 다르게 된다.
호출할때마다 다르게 정의되는 This
브라우저 -window
node.js -global
function a(){
console.log(this) // 전역객체
}
function b(){
console.log(this) // 전역객체
function c(){
console.log(this) //전역객체
}
c()
}
b()
var a = {
b: function () {
console.log(this);
},
};
a.b()
var a = {
b: {
c: function () {
console.log(this);
},
},
};
a.b.c(); // a.b 까지가 this
명시적 this 바인딩의 3가지 방법(call, apply, bind) this를 지정해 줄수 있다.
function a(x, y, z) {
console.log(this, x, y, z);
}
var b = {
bb: "bbb",
};
a.call(b, 1, 2, 3);
a.apply(b, [1, 2, 3]);
var c = a.bind(b);
c(1, 2, 3);
var d = a.bind(b, 1, 2);
d(3);
call, apply 모두 첫번째 자리에 this를 명시해 줄수 있으며, bind역시 this를 명시해줄수 있다.
모두 동일하게 this를 출력하고 있다.
제어권을 가진 함수가 콜백의 this를 지정해둔 경우도 있다(setTimeout, addEventListner)
다만 이 경우에도 this를 바인딩해서 콜백으로 넘기면 변경 가능하다
var callback = function (){
console.dir(this)
}
var obj = {
a: 1
}
setTimeout(callback,100)
setTimeout에서는 전역객체가 나오게 된다.
document.body.innerHtml += '<div id="a">클릭하세요</div>';
document.getElementById("a").addEventListener("click", function () {
console.dir(this);
}); // obj를 this로 하고 싶으면 bind.obj
addEventListner는 별도로 지정된 this가 있다.
생성자함수의 내용을 바탕으로 인스턴스 객체를 만드는 명령이니 만들어진 인스턴스가 객체가 된다.
function Person(n, a) {
this.name = n;
this.age = a;
}
var jay = Person("상기", 31);
console.log(window.name, window.age)
new 연산자를 사용시 전역객체에 할당이 된다.
new 연산자를 사용해 인스턴스 객체를 만들면 객체가 새로 만들어지면서 this 바인딩 된다.
function Person(n, a) {
this.name = n;
this.age = a;
}
var jay = new Person("상기", 31);
console.log(jay)