웹 프로그래밍 기초/객체

생성자 함수를 이용한 객체 정의

별초롱언니 2025. 4. 7. 11:15

같은 속성과 메서드를 가진 여러개의 객체를 정의하려면 앞선 코딩을 반복 정의해야한다. 

이를 위하여 먼저 객체 설계도(생성자 함수)를 정의하고, 설계도대로 찍어내면 된다.

 

객체를 생성하기 위해 'new' 연산자를 활용한다. 

자바스크립트는 다른 언어와 달리 'class' 라는 개념이 없다. 대신 생성자 함수가 그 역할을 대신한다.

이러한 생성자 함수를 이용하여 생성된 객체럴 '인스턴스'라고 한다.

 

function 생성자함수명 (매개변수1, 매개변수2,...,매개변수n) {

this.속성1 = 매개변수1;

...

 this.속성n = 매개변수n;

  this.메서드1 = function() {함수구문};

this.메서드2 = function() {함수구문};

}

let obj = new 생성자함수명(인자값1, ... , 인자값n);

this

자기 자신의 객체를 호출 할 때 사용한다. 

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    function Car (model, speed, color) {
      this.model = model;
      this.speed = speed;
      this.color = color;
      this.break = function () {
        this.speed -=10;
      };
      this.accel = function() {
        this.speed += 10;
      };
    }
    let myCar = new Car("BMW", 100, "black");
    let yourCar = new Car("Benz", 150, "gray");
    
    document.write("myCar.model : " + myCar.model + ", 속도 : " + myCar.speed + ", 색상 : " + myCar.color + "<br>");

    yourCar.accel();
    document.write("yourCar.model : " + yourCar.model + ", 속도 : " + yourCar.speed + ", 색상 : " + yourCar.color + "<br>")
  </script>
</body>
</html>

'웹 프로그래밍 기초 > 객체' 카테고리의 다른 글

class문법 활용한 객체 정의  (0) 2025.04.07
class문법 활용한 객체 정의  (0) 2025.04.07
사용자 정의 객체  (0) 2025.04.07
메서드  (0) 2025.04.07
객체란  (0) 2025.04.07