
this 는 현재 실행 중인 코드에서 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수이다.
this가 가리키는 값, 즉 this 의 바인딩은 함수 호출 방식에 의해 동적으로 결정된다.
this 가 가리키는 객체this : 전역 객체this : 해당 메소드를 호출한 객체this : 지정되지 않음this기본적으로 this 에는 전역 객체(window)가 바인딩 된다.
console.log(this); // window
this메서드로서 호출된 함수 내부에서 this는 해당 메서드가 속한 객체를 가리킨다.
const person = {
name: "Yun",
sayName() {
console.log(this.name);
},
};
person.sayName(); // Yun
this함수를 호출했을 때 그 함수 내부의 this는 지정되지 않는다.
this가 지정되지 않은 경우, this는 자동으로 전역 객체를 바라보기 때문에
함수를 호출하면 함수 내부에서의 this는 전역 객체가 된다.
const myFunc = function () {
console.log(this);
};
myFunc(); // window
❓ 아래 상황에서의 출력은 어떻게 될까?
const person = {
name: "Yun",
func1: function () {
const func2 = function () {
console.log(this.name);
};
func2();
},
};
person.func1();
💡 정답은... undefined 가 출력된다!
.func1() 메소드 호출 시 내부 함수 .func2()가 실행됨.func2() 내부의 this는 지정되지 않아서 곧 전역 객체를 가리킴name이란 속성은 존재하지 않으므로 undefined가 뜸❗ 여러모로 복잡하고 전혀 의도했던 바가 아니다.
이걸 어떻게 해결할 수 있을까?? ⇒ Arrow Function!
ES6(ECMAScript 6)에서 도입된 JavaScript의 간결한 함수 표현식
// 일반 함수 표현식
const add = function (x, y) {
return x + y;
};
// 화살표 함수 표현식
const add = (x, y) => x + y;
// 매개변수가 하나일 때 괄호 생략 가능
const square = (x) => x * x;
// 매개변수가 없을 때 괄호 필요
const greet = () => "Hello!";
this 바인딩 차이Arrow Function은 this를 자신이 정의된 상위 스코프의 this로 고정한다.
const person = {
name: "Yun",
func1: function () {
const func2 = function () {
console.log(this.name);
};
func2();
},
};
person.func1(); // undefined
일반 함수 호출 시 this 는 전역 객체인 window 를 가리킨다.
window 객체에는 name 값이 없으므로 undefinded 가 나온다.
이 경우 func2를 Arrow function 으로 바꿔주면 의도한 결과가 나온다.
const person = {
name: "Yun",
func1: function () {
const func2 = () => {
console.log(this.name);
};
func2();
},
};
person.func1(); // Yun
Arrow function 은 this를 자신이 정의된 상위 스코프의 this로 고정하므로, person 객체를 가리키게 되어, name 값인 Yun이 나온다.
화살표 함수는 this가 고정되어 있기 때문에 생성자 함수로 사용할 수 없다.
const Person = (name) => {
this.name = name;
};
// TypeError: Person is not a constructor
const alice = new Person("Alice");
arguments 객체가 없다일반 함수에서는 모든 parameter에 접근하는 유사 배열 객체인 arguments 가 존재했다.
그러나, 화살표 함수에는 arguments 객체가 없다.
function showArgs() {
console.log(arguments);
}
showArgs(1, 2, 3); // [1, 2, 3]
const showArgsArrow = () => {
console.log(arguments);
};
showArgsArrow(1, 2, 3); // ReferenceError: arguments is not defined
만약, 화살표 함수에서도 모든 parameter 에 접근하고 싶다면 rest parameter인 ...args 을 사용하자!
const showArgsArrow = (...args) => {
console.log(args);
};
showArgsArrow(1, 2, 3); // [1, 2, 3]