모든 함수 scope내에서 자동으로 설정되는 특수한 식별자
this; // Window {}
function a() { console.log(this); };
a(); // Window {}
var obj = {
a: function() { console.log(this); },
};
obj.a(); // obj
위의 함수를 아래의 상황으로 만들면 this의 값이 달라진다.
var a2 = obj.a;
a2(); // window
호출할때 함수가 그냥 함수인지 메소드인지가 중요하다. a2는 obj.a를 꺼내온 것이기 때문에 함수가 된다.
let obj2 = {
hello: {
fn : function(){console.log(this)}
}
}
obj2.hello.fn() // hello
위의 함수는 바로위의 부모object를 가르키는 것을 알 수 있다.
*주의 : 내부함수 우회시!!
콜백함수의 this는 전역객체인 window가 실행된다. 내부함수의 우회시 함수내부에서 메소드가 아닌 함수가 호출이 되면 window가 객체가 되는 것과 같은 원리이다.
하지만 call, apply, bind를 이용해서 this를 바인딩해서 지정해줄 수 있다.
또는 setTimeout이나 EventListener 등과 같은 제어권을 가진 함수가 callback의 this를 명시한 경우 그에 따른다.
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHi = function() {
console.log(this.name, this.age);
}
위 함수에서 this는 Person이다.
function identify(){
return this.name.toLocaleUpperCase();
}
var me = {name:"Kyle"};
var name = "bom";
identify() // "BOM" , this가 window
identify.call(me) // "KYLE" , this가 me
위 함수는 call을 사용해서 this를 직접적으로 명시한다.
var add = function (x, y){
this.val = x + y;
}
var obj = {
val:0
};
add.apply(obj, [2, 8]);
console.log(obj.val); // 10
add.call(obj, 2, 8);
console.log(obj.val); // 10
zerocho : https://www.zerocho.com/category/JavaScript/post/5b0645cc7e3e36001bf676eb