TIL/멋쟁이사자처럼 FE스쿨 2기

[Day 34] JS 객체지향프로그래밍; 생성자함수, 프로토타입, 객체 상속

Dahee.jo 2022. 5. 17. 23:36
SMALL

본 내용으로 들어가기 전,

<body>
<h1>나의 todo list</h1>
<p>1. 오늘 저녁에는 부대찌게를 끓여 먹겠다.<button type="button">삭제</button></p>
<p>2. 후식으로 슈팅스타를 먹겠다.<button type="button">삭제</button></p>
<p>3. 자기 전에 반드시 내일 아침 메뉴를 생각해두겠다.<button type="button">삭제</button></p>

<script>
    const todos = document.querySelectorAll('p');
    // 콘솔 로그할 때 노드리스트로 출력된다.
    const delBtns = document.querySelectorAll('button');

    todos.forEach(todo=>{
        todo.addEventListener('click',(e)=>{
            alert(e.target.firstChild.textContent);
            // alert(e.target.textContent.slice(0,-2));
        })
    })
    // 노드리스트인 경우 포이치 쓰면 익스 지원 불가

    // 익스에서 노드리스트로 사용하고 싶을 때
    // Array.prototype.forEach.call(todos, (item)=>{
    //     alert(e.target.textContent.slice(0,-2));
    // })

    delBtns.forEach(btn=>{
        btn.addEventListener('click',(e)=>{
            e.stopPropagation(); 
            if(window.confirm('삭제하시겠습니까?')) {
            btn.parentElement.remove();    
            }
        })
    })


    //이벤트위임을 이용해서 쓴 방법(동기분 코드)

    document.body.addEventListener("click", function (e) {
      console.log(e.target.nodeName);
      if (e.target.nodeName === "BUTTON") {
        if (confirm("삭제할꺼야?")) {
          e.target.parentNode.remove();
        }
      } else if (e.target.nodeName === "P") {
        alert(
          e.target.textContent.replace(
            e.target.firstElementChild.textContent,
            ""
          )
        );
      }
    });
</script>
</body>

preventDefault()

stopPropagation()의 차이에 대해 코드로 간단 정리~

 

 

 

생성자함수(Constructor)에 대해 이전에 포스팅한 글이 있다:)

https://daheejo.tistory.com/45?category=1258675 

 

[JS] Constructor Function

*freecodecamp 를 기반으로 작성하였다. Constructor Function 컨스트럭터(Constructor)는 새로운 객체를 만드는 함수이다. 이것은 새로운 객체에 속하는 프로퍼티나 기능을 정의한다. function Bird() { this.nam..

daheejo.tistory.com

(기본적인 내용은 여기서 보는걸로 하고 ㅎ)

 

한 생성자를 통해 만들어진 여러 객체들은 같은 프로퍼티와 메서드를 공유한다.

 

function NewFactory(name){
    this.name = name;
    this.sayYourName = function(){
        console.log(`삐리비리 제 이름은 ${this.name}입니다.`)
    }
}

const robot1= new NewFactory('재현');
//생성자함수 안의 this는 인스턴스를 가리킴




function PickAFood(arr){
    this.food = arr[Math.floor(Math.random()*arr.length)];
}

let foodOftheDay = new PickAFood(['피자','자장면','스테이끼','부레이끼'])
console.log(foodOftheDay);

Prototype

 

이렇게 생성자함수를 통해 객체를 쉽게 양산해낼 수 있지만, 문제는

그 객체의 메서드를 등록할 때마다 새로운 함수를 만들어낸다는 점이다.

이러한 문제를 해결하기 위한 것이 바로 프로토타입이다.

 

function NewFactory2(name){
    this.name = name;
}

NewFactory2.prototype.sayYourName = function(){
    console.log(`삐리비리. 제 이름은 ${this.name}입니다. 주인님.`);
}

프로토타입은 객체에서 나온 모든 인스턴스가 하나의 메서드를 공유하도록 한다.

 

 


객체의 상속

 

//부모역할 생성자함수
function Parent() {
    this.name = '재현';
}
Parent.prototype.rename = function (name) {
    this.name = name;
}
Parent.prototype.sayName = function () {
    console.log(this.name);
}

//자식역할 생성자함수
function Child() {
    Parent.call(this); //parent의 this로 변경
}

Child.prototype = Object.create(Parent.prototype);//부모와 연결된 메서드를 상속한다
Child.prototype.canWalk = function () {
    console.log('now i can walk!!');
}
반응형