this 바인딩

김하은·2023년 5월 4일
0
  • new를 사용했을때 해당 객체로 바인딩됨.
let name = "global";
function Func() {
  this.name = "Func";
  this.print = function f() { console.log(this.name); };
}
let a = new Func();
a.print(); // Func
  • call,apply,bind등 명시적인 바인딩을 사용했을때 인자로 전달된 객체에 바인딩됨.
function func() {
  console.log(this.name);
}

const obj = { name: 'obj name' };
let.call(obj); // obj name
func.apply(obj); // obj name
(func.bind(obj))(); // obj name
  • 객체의 메소드로 호출할 경우 해당 객체에 바인딩됨.
const obj = {
  name: 'obj name',
  print: function p() { console.log(this.name); }
};
obj.print(); // obj name

console이라는 객체의log라는 메소드에 this.name을 넣었다.
따라서 여기서의 this는 obj라는 객체를 의미한다.

  • 그 외
    - strict모드에서는 undefined로 초기화되고,
    • 일반적으로 브라우저의 경우에서 this는 window객체에 바인딩된다.

0개의 댓글