화살표 함수를 사용해서 안 되는 경우
const person = {
name: 'Sally',
sayHi: () => console.log(this.name)
}
person.sayHi() // undefined
메소드를 호출한 객체를 가리키지 않고, 상위 컨텍스트인 window를 가리킨다.
const Foo = () => {} // x
console.log(Foo.hasOwnProperty('prototype')); // false
const foo = new Foo() // TypeError: Foo is not a constructor
var button = document.getElementById('myButton');
// Bad
button.addEventListener('click', () => {
console.log(this === window); // => true
this.innerHTML = 'Clicked button';
});
// Good
button.addEventListener('click', function() {
console.log(this === button); // => true
this.innerHTML = 'Clicked button';
});
Quiz
const obj = {
a: 'a',
test: function () {
console.log(this.a);
const arrow = () => {
console.log(this.a);
};
arrow();
},
};
const obj2 = {
a: 'b',
};
obj.test() - 1 // a a
obj.test.call(obj2) - 2 //
const func = obj.test;
func() - 3
그 외 용어