JavaScript/Javascript

this 바인딩

58청춘 2023. 9. 22. 17:25
728x90

this 바인딩

EC(Execution Context) 가 생성될 때마다 this 바인딩이 발생하며, 우선순위 순으로 나열하면 아래와 같다.

 

this 바인딩 되는 순서

1. new를 사용했을 때 해당 객체로 바인딩된다.

var name = "global";
function Func() {
  this.name = "Func";
  this.print = function f() { console.log(this.name); };
}
var a = new Func();
a.print(); // Func

 

2. call, apply, bind 와 같이 명시적 바인딩을 사용한 경우 인자로 전달된 객체에 바인딩 된다.

function func() {
  console.log(this.name);
}

var obj = { name: 'obj name' };
func.call(obj); // obj name
func.apply(obj); // obj name
(func.bind(obj))(); // obj name

 

 

3. 객체의 메소드로 호출할 경우 해당 객체에 바인딩 된다.(암시적 바인딩)

var obj1 = {
  name: 'obj name',
  print: function p() { console.log(this.name); }
};
obj1.print(); // obj name

function hello () {
  console.log(this.name);
}

var obj2 = {
  name: 'chris',
  hello: hello,
}

helloFn = obj.hello;

name = "global context";

helloFn() // global context

 

 

4. 그 외의 경우

  • strict mode - undefined로 초기화 된다.
  • 일반 - 브라우저라면 window객체에 바인딩 된다.

 

 

참고 자료

1. https://jeonghwan-kim.github.io/2017/10/22/js-context-binding.html#%EC%95%94%EC%8B%9C%EC%A0%81-%EB%B0%94%EC%9D%B8%EB%94%A9%EA%B3%BC-new-%EB%B0%94%EC%9D%B8%EB%94%A9%EC%9D%98-%EC%9A%B0%EC%84%A0%EC%88%9C%EC%9C%84

 

2.https://github.com/baeharam/Must-Know-About-Frontend/blob/main/Notes/javascript/this.md

 

728x90