javascript _this

장봄·2020년 5월 26일
0

code-states_4주차

목록 보기
8/13
post-thumbnail

[this]

모든 함수 scope내에서 자동으로 설정되는 특수한 식별자

패턴

1. Global(전역공간) : this는 window이다(node.js에서는 this가 global이다)

this; // Window {}

2. Function호출시 : this는 window이다

function a() { console.log(this); };
a(); // Window {}

3. Method호출시(객체에 담긴 함수) : this는 부모 object이다

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를 가르키는 것을 알 수 있다.

*주의 : 내부함수 우회시!!

4. callback 호출시 : 기본적으로 함수내부에서와 동일

콜백함수의 this는 전역객체인 window가 실행된다. 내부함수의 우회시 함수내부에서 메소드가 아닌 함수가 호출이 되면 window가 객체가 되는 것과 같은 원리이다.

하지만 call, apply, bind를 이용해서 this를 바인딩해서 지정해줄 수 있다.

또는 setTimeout이나 EventListener 등과 같은 제어권을 가진 함수가 callback의 this를 명시한 경우 그에 따른다.

5. Construction mode(new 연산자로 생성된 function영역의 this) : 새로 생성된 객체(instance)

function Person(name, age) {
 this.name = name;
 this.age = age;
}
Person.prototype.sayHi = function() {
 console.log(this.name, this.age);
}

위 함수에서 this는 Person이다.

6. .call or .apply호출 : call, apply의 첫번째 인자로 명시된 객체

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

profile
즐겁게 배우고 꾸준히 블로깅하는 개발자입니다 ;>

0개의 댓글