자바스크립트의 this
는 함수의 호출에 따라 값이 변화한다. 다르게 말하면 누가 실행을 했는지에 따라 값이 결정된다고도 이야기 할 수 있다. 실행 콘텍스트(context) 실행 문맥으로도 볼 수 있다.
this
를 실행할 수 있는 방법에는 4가지가 있다.
함수 안에서 사용했을 경우 함수를 실행하는 주체에게 this가 바인딩 된다.
function exFunction () {
return this;
}
console.log(exFunction()); //window
위 코드에서 함수를 실행하는 주체는 window이기 때문에 this는 window이다.
strict 모드에서는 함수 안에서 실행한 this는 undefined
로 설정 되어 있다. strict 모드는 엄격한 환경에서 코드를 실행하며 자바스크립트가 묵인한 에러를 에러로 잡는다. 엄격하게 문법 검사를 하겠다는 뜻으로 이해하면 될 것 같다.
일반 함수가 아닌 메소드(dot notation) 안에서 실행한 this는 해당 메소드에 바인딩 된다. 점 앞에 있는 객체가 this로 설정이 된다.
let myFriend = {
name: 'Emily',
age: 35,
greeting: function greeting() {
console.log (`Hello, I\'m ${this.name} and ${this.age}years old!`);
}
};
myFriend.greetings(); // 'Hello, I'm Emily and 35 years old!'
let collegeYear = 'Freshman';
let myYear = {
collegeYear: 'Junior',
shoutOut: function shoutOut() {
console.log(this.collegeYear);
}
};
let yourYear = {
collegeYear: 'Sophomore',
shoutOut: myYear.shoutOut
};
myYear.shoutOut(); //'Junior'
yourYear.shoutOut(); //'Sophomore'
shoutOut(); //'Freshman'
apply(), bind(), call() 메소드를 통해 실행하면 this는 인자로 명시된 객체에 바인딩이 된다. 해당 메소드를 통해 인자로 넘어온 객체가 해당 this의 값이라고 짝을 지어주는 것이다.
let collegeYear = 'Freshman';
function shoutOut() {
console.log(this.collegeYear);
};
let myYear = {
collegeYear: 'Junior';
};
let yourYear = {
collegeYear: 'Sophomore',
};
shoutOut(); //'Freshman'
shoutOut.apply(myYear); //'Junior'
shoutOut.call(yourYear) //'Sophomore'
apply(), call()은 바로 값을 리턴하지만 bind()의 경우는 아니다. bind()는 다시 한번 함수를 실행해야 값을 리턴한다.
new와 함께 실행한 함수는 새로운 객체가 생겨 함수를 실행한다. new 키가 사라지면 this는 실행한 주체에 따라 바인딩이 달라진다.
function Function() {
this.name = 'new function!';
};
let newExample = new Function();
console.log(newExample)
/* {
name: new function!} 객체가 생성, 리턴 */
function Friend (name) {
this.name = name;
console.log(this.name);
}
let Alyssa = new Friend('alyssa');
let Emily = new Friend('emily');
new Friend(Alyssa.name); //'alyssa'
new Friend(Emily.name); //'emily'
this
는 거의 대부분의 상황에서 객체이다.