-
카테고리
-
세부 분야
풀스택
-
해결 여부
해결됨
this 관련 문의드립니다.
22.01.14 23:08 작성 조회수 160
0
node.js 교과서로 공부중에 궁금한것이 있습니다.
화살표 함수는 본인의 대한 this를 갖지 않는다는것인데요. 때문에 화살표 함수가 없던 시절에 메서드 내부에 콜백함수 안에서 this를 사용해 매서드 외부의 객체(friends)를 참조하기 위해서 매서드 내부에서 this값을 가지는 변수를 선언하고 콜백함수에서 그값으로 참조를 하였죠.
const relationship1 = {
name: "zero",
friends: ["nero", "hero", "xero"],
logFriends: function () {
const that = this; // this는 relationship1을 가리킨다.
this.friends.forEach(function () {
console.log(that.name, that.friends);
});
},
};
relationship1.logFriends();
그리고 화살표 함수가 생긴 이후로는 이런코드를 작성하구요.
const relationship2 = {
name: "zero",
friends: ["nero", "hero", "xero"],
logFriends() {
this.friends.forEach(() => {
console.log(this.name, this.friends);
});
},
};
relationship2.logFriends();
그런데 궁금한것이 logFriends역시 함수인데 logFriends는 화살표 함수를 쓰지 않아도 this.friends로 메서드 외부에 friends에 접근 할 수 있다는 것이 신기하네요. 그래서 제가 함수 프로퍼티를 화살표함수로 만드는 시도를 했습니다.
const relationship3 = {
name: "zero",
friends: ["nero", "hero", "xero"],
logFriends: () => {
console.log(this.friends);
},
};
relationship3.logFriends();
하지만 이렇게 하면 undefined가 출력되더군요. 두번째 코드의 logFriends가 함수 프로퍼티라 가능한건가요??
답변을 작성해보세요.
답변 1