var ㅁ = function () {
// ...
};
var a = () => {
//...
};
() => 10+20; // {} 필요없음
() => {
print();
let();
return 10+20;
};
const a = num => {
return num * 10;
};
const b = num => num*10;
a(10); // 100
b(10); // 100
화살표 함수에서 사용되는 this 바인딩은 기존함수 this와 다른 방식을 가지고있다
화살표 함수의 this는 함수를 선언할 때의 상위 스코프의 this로 바인딩 될 객체가 정해진다.
const foo = {
name: "bar",
age: 10,
printThis() {
console.log(this); // {name: "bar", age: 10, printThis: f}
const innerFunc = () => {
return this; // {name: "bar", age: 10, printThis: f}
};
}
console.log(inerFunc());
}
};
foo.printThis();
innerFunc의 상위 스코프는 printThis이기 때문에 printThis의 내부 this와 innerFunc의 내부 this는 같은 값으로 바인딩 된다.
일반 함수에서 setTimeout에서의 this는 window를 가르키지만
화살표 함수에서는 상위 스코프의 this로 값이 바인딩 된다.
const foo = {
name: "bar",
age: 10,
getThisarrowFunc function() {
console.log(this); // {name: "bar", age:10, getThisarrowFunc: f}
setTimeout(() => {
console.log(this); // {name: "bar", age:10, getThisarrowFunc: f}
}, 1000);
},
getThisFunc: function() {
console.log(this); // {name: "bar", age:10, getThisFunc: f}
setTimeout(function() {
console.log(this) // window
}, 1000)
}
};
foo.getThisArrowFunc();
foo.getThisFunc();
그러나 엄격모드('use strict') 일때는 바인딩 되지 않는다.
"use strict" // 엄격모드
(function() {
setTimeout(() => {
console.log(this); // undefined 이 경우는 this 가 바인딩 되지 않는다
}, 1000);
})();
addEventListener의 두 번째 인자로 화살표 함수를 넣으면 this는 상위 스코프의 this를 가르킨다.
const button = document.getElementById("this-button");
button.innerText = "함수 호출 버튼";
button.addEventListener("click", () => {
console.log(this === window); // true
console.log(this.innerText); // undefined
});
화살표 함수가 아닌 일반 함수를 사용해준다.
일반 함수로 정의된 addEventListener 함수의 this 는 currentTarget 을 가리킨다.
const button = document.getElementById("this-button");
button.innerText = "함수 호출 버튼";
button.addEventListener("click", function() {
console.log(this === button); // true
console.log(this.innerText); // 함수 호출 버튼
});
는 class로 생성된 개체 인스턴스를 가리킨다
class Foo {
constructor() {
this.name = "bar";
}
register() {
window.addEventListener("keydown", e => this.shomMethod(e));
}
someMethod(event) {
console.log(this.name); // bar
console.log(event.keyCode); // Enter 입력시 63
}
}
const baz = new Foo();
baz.register();
일반 함수의 this와 다르게 화살표 함수에서의 this는 call,bind,apply 메소드로 this 에 바인딩된 값을 변경할 수 없다.
this.foo = "bar";
const normalFunc = function() {
return this.foo;
};
const arrowFunc = () => this.foo;
console.log(normalFunc.cll({ foo: "baz" }) // baz
console.log(arrowFunc.cll({ foo: "baz" }) // bar 화살표 함수는 this값 변경 불가
const Foo = () => {};
const foo = new Foo(); // Uncaught TypeError: Foo is not a constructor
출처 : [https://joshua1988.github.io/vue-camp/]