🗃️javascript/DOM 조작

js 객체 생성(생성자, class), 상속

하얀성 2023. 4. 13. 20:27

.writeln()은 문서에 문자, 코드 등을 쓰는 메서드입니다.

. write()와 다른 점은 줄바꿈 기호가 들어간다는 것입니다.


<생성자 객체 생성, 리터럴 객체 생성>

생성자 객체 생성방식은 생성자 함수를 먼저 선언한 후, 필요할 때마다 함수를 불러서 쓰는 방식.

<script>
    // 객체를 생성자 방법으로 생성하기
   function Student(age, ban) {
    this.age = age;
    this.ban = ban;
   }
   let myStudent = new Student(13, 2)
   document.write(myStudent.ban)

   // 객체를 리터럴 방법으로 생성하기
   let myCity = {
    aker: "34h",
    name: "ohio"
   }
  </script>

<class 객체 생성>

생성자 객체 생성방식은 상속에서 문제가 발생할 수 있음. 

그래서 class를 통해 객체를 생성할 수 있음.

 

class에 속성을 부여하기 위해서는 constructor() 선언 필수.

클래스 선언의 맨 앞자리는 무조건 대문자!

객체는 'myArr' 이렇게 중간 대문자 변수이름 생성

 

constructor(속성 변수){속성 선언} 함수는 생성자 메서드임. 고유함수임.

이 constructor 메서드를 정의해야만  생성자 호출시에 빈 생성자가 나오지 않음.

 

클래스 안에서는 원하는 만큼 메서드 추가가 가능한데, age()도 추가한 메서드이다. 

<body>
  <h2 id="test"></h2>
  <script>
    class Dog {
      constructor(name, adoptedYear) {
        this.name = name;
        this.adoptedYear = adoptedYear;
      }
      age() {
        let date = new Date();
        return date.getFullYear() - this.adoptedYear;
      }
    }
    let myDog = new Dog("Mary",2013);
    document.getElementById("test").innerHTML = "이름은" + myDog.name + "나이는" + myDog.age()
  </script>

</body>

<상속>

extends와 super을 통해 또 속성 선언 없이 Animal의 속성값을 Dog에 받아왔다.

class Dog만 객체로 선언했는데 Animal 클래스까지 쓸 수 있게 된것이다.

<body>
  <h2 id="test"></h2>
  <h2 id="test1"></h2>
 
<script>
  class Animal {
    constructor(weight) {
      this.weight = weight;
    }
  }
  class Dog extends Animal {
    constructor(name, adoptedYear, weight) {
      super(weight);
      this.name = name;
      this.adoptedYear = adoptedYear;
    }
    age() {
      let date = new Date();
      return date.getFullYear() - this.adoptedYear
    }
  }
  let myDog = new Dog("Mary", 2013, 20);
  document.getElementById("test").innerHTML =
    "내 강아지 이름은" + myDog.name + "이고, 나이는 " + myDog.age() + "살입니다.";
  document.getElementById("test1").innerHTML =
    "체중은 "+ myDog.weight
</script>
</body>


1. 객체 student를 클래스 Student 를 통해 정의해보자.

2. 클래스 Student를 Person클래스로부터 상속받아 속성을 부여해보자.

 

<body>
  <h2 id="test"></h2>
 
  <script>
    class Person {
      constructor(eye) {
        this.eye = eye;
      }
    }
    class Student extends Person{
      constructor(eye,weight) {
        super(eye)
        this.weight = weight;
      }
    }
    let student = new Student(2, 60);
    document.getElementById("test").innerHTML = "눈 갯수는 "+student.eye +"이고, 학생 몸무게는 "+ student.weight
  </script>
</body>

<배열에 값 저장하기>

(무명함수를 사용했다. onclick="a"하면 오류가 발생한다. "a()"로 해줘야 한다.)

<body>
  <input type="text" id="a"> <button onclick="a()">append</button>
  <p id="result"></p>
  <script>
    let array = [];

    let a = function() {
      array.push(document.getElementById("a").value);

      let str = "";
      for (let i = 0; i < array.length; i++) {
        str += "array[" + i + "] = " + array[i] + "<br/>";
      }
      document.getElementById("result").innerHTML = str;
    }

  </script>
</body>

 

-결과-