this 문법

Sasha Park·2021년 4월 8일
0

this

함수 실행 시 호출(invocation) 방법에 의해 결정되는 특별한 객체. 비엄격 모드에서 항상 객체를 참조하며, 엄격 모드에서는 어떠한 값도 될 수 있음. 영어의 '지시대명사'의 기능과 동일해 보임. 실행되는 맥락(execution context)에 따라 따르게 결정. 화살표 함수와는 완전 상극이므로 같이 쓰면 안된다.

user.printName() -> user가 this
user.company.printName() -> user.company가 this

매 상황마다의 this.

  1. 함수호출.
    기본적으로 this는 전역 객체(global object)에 바인딩된다. 즉, 일반함수에 쓰인 this는 기본적으로 window를 나타내고, 내부함수도 동일하게 적용.
function foo() {
  console.log("foo's this: ",  this);  // window
  function bar() {
    console.log("bar's this: ", this); // window
  }
  bar() // Window
}
foo() // Window

method의 내부 함수도 this 전역객체에 바인딩 됨.

  1. Method 호출
    obj.foo() // class 안에 있는 함수
var obj1 = {
  name: 'Lee',
  sayName: function() {
    console.log(this.name);
  }
}

var obj2 = {
  name: 'Kim'
}

obj2.sayName = obj1.sayName;

obj1.sayName(); // lee
obj2.sayName(); // kim
  1. new 키워드를 이용한 생성자 호출

일반 함수를 호출하면 this는 전역객체에 바인딩되지만 new 연산자와 함께 생성자 함수를 호출하면 this는 생성자 함수가 암묵적으로 생성한 빈 객체에 바인딩된다.

function Person(name) {
  this.name = name;
}

var me = new Person('Park');
console.log(me); // {name: "Park"}
  1. .call또는 .apply 호출
    foo.call()
    foo.apply()

new 키워드를 이용한 생성자(class),
.call /.apply 호출: 첫번째 인자로 전달된 객체

profile
'어?' 에서 '아!'가 되는 순간을 즐기는 개발자입니다.

0개의 댓글