본문 바로가기
코딩이야기𖦹/오답노트

📝 [250318/오답노트] 자바스크립트 객체 & 생성자 함수, 그리고 타이머 실수 정리

by Dev디자인 2025. 3. 18.

1. setIntervalclearInterval 사용 실수 ⚠️

❌ 내가 쓴 코드

let timer;
timer = setInterval(function () {
  console.log("현재 시각 업데이트 중...");
}, 1000);

const button = document.getElementById('stop');
button.addEventListener("click", function(){
    clearInterval(nowTime); // ❌ 'timer'가 아닌 'nowTime'을 사용했음
})

✅ 올바른 코드

let timer = setInterval(function () {
  console.log("현재 시각 업데이트 중...");
}, 1000);

const button = document.getElementById('stop');
button.addEventListener("click", function(){
    clearInterval(timer); // ✅ 'timer'를 사용해야 함
    console.log("시계가 정지되었습니다.");
});

💡 실수 요약:

  • clearInterval()의 매개변수로 setInterval()의 반환값인 timer를 넣어야 함.
  • 잘못된 변수(nowTime)를 사용하면 clearInterval()이 정상적으로 작동하지 않음.

2. new Date() 사용 실수 🕒

❌ 내가 쓴 코드

const nowTime = new Date();
let hour = now.getHours(); // ❌ 'now'라는 변수가 없음
let minute = now.getMinute(); // ❌ 메서드 이름이 틀림
let second = now.getSecond(); // ❌ 메서드 이름이 틀림
const nowTime = new Date();
let hour = nowTime.getHours(); // ✅ 'nowTime'을 사용해야 함
let minute = nowTime.getMinutes(); // ✅ 'getMinute()' → 'getMinutes()'
let second = nowTime.getSeconds(); // ✅ 'getSecond()' → 'getSeconds()'

💡실수 요약:

  • new Date()로 만든 객체를 사용할 때는 정확한 변수명을 사용해야 함.
  • getMinute(), getSecond()는 존재하지 않으며, 올바른 메서드는 getMinutes(), getSeconds()임.

3. 객체 리터럴 방식 실수 🚗

❌ 내가 쓴 코드

const dreamCar = {
  brand: Jeep, // ❌ 문자열은 따옴표로 감싸야 함
  model: Wrangler, // ❌ 문자열을 따옴표로 감싸지 않음
  year: "2024" // ✅ 숫자를 문자열로 저장하면 숫자 연산이 어려움
};

✅ 올바른 코드

const dreamCar = {
  brand: "Jeep", // ✅ 문자열은 따옴표로 감싸야 함
  model: "Wrangler",
  year: 2024 // ✅ 숫자는 그냥 입력하면 됨
};

💡 실수 요약:

  • 문자열은 반드시 **따옴표('' 또는 "")**로 감싸야 함.
  • 숫자는 그냥 입력해야 함 ("2024"가 아니라 2024).

4. 생성자 함수 실수 🎯

❌ 내가 쓴 코드

function Car(brand, model, year) {
  brand: ['Jeep'], // ❌ this.brand = brand; 로 작성해야 함
  model: 'Wrangler',
  year: 2024,
  myDreamCar: function(){ // ❌ 메서드는 객체 내부에서 this로 정의해야 함
    console.log(`제 드림카는 ${year}년식 ${brand}회사의 ${model}입니다.`);
  }
}

✅ 올바른 코드

function Car(brand, model, year) {
  this.brand = brand; // ✅ this를 사용
  this.model = model;
  this.year = year;

  this.myDreamCar = function() {
    console.log(`제 드림카는 ${this.year}년식 ${this.brand} 회사의 ${this.model}입니다.`);
  };
}

const dreamCar1 = new Car("Jeep", "Wrangler", 2024);
dreamCar1.myDreamCar(); // ✅ 정상 출력

💡 실수 요약:

  • 생성자 함수 내부에서는 속성을 this.속성명 = 값; 형태로 할당해야 함.
  • 메서드는 객체 속성으로 this.메서드명 = function() {...} 형식으로 정의해야 함.
  • 템플릿 리터럴(`)에서 this를 반드시 사용해야 함 (${this.year} 등).

this를 꼭 써야하는 이유는 뭘까?

this는 생성자 함수가 만든 새 객체를 가리킨다. this.brand = brand;처럼 사용해야 객체 속성으로 저장된다.
그렇기 때문에 this 없이 선언하면 지역 변수로 처리되어 객체에 저장되지 않는다. 메서드에서도 this.year처럼 사용해야 객체 속성을 참조할 수 있다. 즉, this를 사용해야 생성자 함수가 객체를 제대로 동작하게 만든다! 🚀

🔥 마무리: 실수하지 않으려면?

setIntervalclearInterval을 사용할 때는 변수명(timer)을 정확하게 사용하기!
new Date() 객체에서 메서드명을 정확하게 사용하기! (getMinutes(), getSeconds() 등)
✅ 객체 리터럴에서는 문자열은 따옴표, 숫자는 그냥 입력!
✅ 생성자 함수에서는 this를 꼭 사용하고, 메서드는 객체 속성으로 추가하기!

🚀 나는 늘 오타나 뭐 하나 빠트려서 뭐지..? 하는 경우가 많다..다음엔 놓치지않기... ✨

최근댓글

최근글

skin by © 2024 ttuttak