본문 바로가기
Javascript

객체안에 함수에서 변수를 접근할 경우 this를 붙여야한다

by jennyiscoding 2022. 10. 1.

오답)

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를 꼭! 붙이도록!