함수가 선언된 이후에 어떤 환경에서 어떤 객체에 의해 호출되지 예측할 수가 없기 때문에 자바스크립트 함수에서 자기 자신이라는 표현을 사용하는게 엄청 까다로운 일이다.
자바스크립트에서 모든 함수는 this를 가지고 있다. 그리고 함수가 호출 되면 그때 그때 상황에 따라 this가 가리키는 객체가 결정된다. 이렇게 함수가 호출 될 때마다 this가 동적으로 결정되는 것을 "this가 그 객체에 binding 된다"라고 표현한다.
console.log(this); // (1) window
const a = {
name: "realzu",
getName() {
console.log(this);
}
}
a.getName(); // (2) { name: 'realzu', getName: ƒ getName() }
const b = a.getName;
b(); // (3) window
const Foo () => {};
new Foo(); // TypeError: Foo is not a constructor
const Foo () => {};
Foo.hasOwnProperty('prototype'); // false
function normal(a, a) {return a + a;}
console.log(normal(1, 2)); // 4
function normal(a, a, a) {return a + a;}
console.log(normal(1, 2, 3)); // 6
const arrow = (a, a) => a + a;
// SyntaxError: Duplicate parameter name not allowed in this context
const cat = {
name: 'meow',
foo1: function() {
const foo2 = function() {
console.log(this.name);
}
foo2();
}
};
cat.foo1(); // undefined
const cat = {
name: 'meow',
foo1: function() {
const foo2 = () => {
console.log(this.name);
}
foo2();
}
};
cat.foo1(); // meow
addEventListener()의 콜백함수
const button = document.getElementById('myButton');
button.addEventListener('click', () => {
console.log(this); // Window
this.innerHTML = 'clicked';
});
button.addEventListener('click', function() {
console.log(this); // button 엘리먼트
this.innerHTML = 'clicked';
});
원래 addEventListener의 콜백함수에서는 this에 해당 이벤트 리스너가 호출된 엘리먼트가 바인딩되도록 정의되어 있다. 이처럼 이미 this의 값이 정해져있는 콜백함수의 경우, 화살표 함수를 사용하면 기존 바인딩 값이 사라지고 상위 스코프(이 경우엔 전역 객체)가 바인딩되기 때문에 의도했던대로 동작하지 않을 수 있다. 물론 상위 스코프의 속성들을 쓰려고 의도한 경우라면 사용할 수 있다.
[JavaScript] 화살표 함수와 this 바인딩
[JavaScript] This (바인딩 룰, 화살표 함수)
화살표 함수
ES6 In Depth: Arrow functions