[Javascript] This 키워드

studying  · 1 min read

들어가며

  • Javascript에서는 모든 function들은 object methods이다.

예시 1)

const person = {
  firstName: "Aeji",
  lastName: "Jeon",
  fullName: function () {
    return this.firstName + " " + this.lastName;
  },
};
// “Aeji Jeon” is printed.
person.fullName();

예시 2)

function func(a, b) {
  return a + b;
}
func(1, 2);

예시 2)에서의 func 함수는 어느 object에도 속해있지 않다. 하지만 javascript에서는 default global object가 존재한다. HTML내에서 HTML page 자체가 default global object이고 브라우저에서는 이 HTML page object가 browser window이다. 따라서 위의 func 함수는 다음 아래와 같이 호출될 수 있다.

window.myFunction(10, 2);

“this” 키워드

  • javascript에서 “this” 키워드는 “this”가 속해있는 owner object를 나타낸다. 예시 1) 에서 this는 person object를 가리킨다. 즉, person object는 this keyword를 포함하고있는 fullName method의 owner object인 것이다.
var x = this;

만약 “this” 키워드가 위의 코드에서와 같이 홀로 쓰일 경우에는 “this”가 속해있는 owner object는 global object인 [object Window]가 된다.

function func() {
  return this;
}

함수의 경우에도 마찬가지로 this는 global object인 [object Window]를 가리킨다(default binding).

var x = this;
function func() {
  return this;
}

하지만 javascript의 strict mode는 default binding을 허락하지 않기 때문에 stric mode에서 정의된함수 내에서의 “this”는 undefined이다.

  • HTML event handler에서의 “this”는 event가 발생한 HTML element를 가리킨다.
<button onclick="this.style.display='none'">BUTTON</button>

references

  • https://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/