오답)
const TwoDotDistance = {
point1: {
x: 0,
y: 0,
},
point2: {
x: 0,
y: 0,
},
setPoints: function (x1, y1, x2, y2) {
// point1, point2의 값을 세팅합니다.
this.point1.x = x1;
this.point1.y = y1;
this.point2.x = x2;
this.point2.y = y2;
},
calculateDistance: function () {
// 두 점 사이의 거리를 구해, 소숫점 두자리까지 계산하고 문자열을 리턴합니다.
// 결과가 NaN 이라면, 숫자 0을 문자열로 리턴합니다.
let d = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
if (isNaN(d)) return 0;
return d.toFixed(2);
},
};
export default TwoDotDistance;
정답)
const TwoDotDistance = {
point1: {
x: 0,
y: 0,
},
point2: {
x: 0,
y: 0,
},
setPoints: function (x1, y1, x2, y2) {
// point1, point2의 값을 세팅합니다.
this.point1.x = x1;
this.point1.y = y1;
this.point2.x = x2;
this.point2.y = y2;
},
calculateDistance: function () {
// 두 점 사이의 거리를 구해, 소숫점 두자리까지 계산하고 문자열을 리턴합니다.
// 결과가 NaN 이라면, 숫자 0을 문자열로 리턴합니다.
let d = Math.sqrt(
Math.pow(this.point1.x - this.point2.x, 2) +
Math.pow(this.point1.y - this.point2.y, 2)
);
if (isNaN(d)) return 0;
return d.toFixed(2);
},
};
export default TwoDotDistance;
두번째 calculateDistance부분에 함수에서 내부 변수에 접근 시 this.~을 붙이지 않아서 오답이 난거였음!
결론)
앞으로 객체 안에 함수에서 다른 변수를 사용할 경우 this를 꼭! 붙이도록!
'Javascript' 카테고리의 다른 글
함수선언문과 함수표현식의 차이, 호이스팅 (0) | 2022.10.02 |
---|---|
Javascript reduce사용법 (0) | 2022.10.02 |
오답노트) 구조분해할당과 filter사용방법 (0) | 2022.09.29 |
타입변환, {}의중의적표현,this (0) | 2022.09.28 |
자바스크립트에서 비동기 처리가 가능하게 해주는 Web API (0) | 2022.09.21 |