JS 객체 지향 프로그래밍

JS 객체 지향 프로그래밍

- 간단한 배열과 객체의 for문

주의할 점은, 반복문에서 member.name을 할 경우 undefined을 출력하므로 member[name]으로 입력해줘야 함

// 배열 const a = [1, 3, 57, 8]; let i = 0; while (i < a.length) { console.log(i); i++; } // 객체 const member = { manager: "deluze", client: "jijek" }; for (let name in member) { console.log(name, member[name]); }

- class

OOP에 속했던 파이썬의 클래스를 떠올리면 아주 쉽다! JS도 class를 쓸 수 있기 때문이고 class의 구조는 다 비슷하니 쉽게 익힐 수 있다. 주의할 점은 생성자 함수는 대문자로 시작하는 코딩 컨벤션을 지키라는 것.

class Human { //생성자 함수는 반드시 대문자로 시작해야 함 constructor(name, nationality) { //constructior는 일종의 __init__ this.name = name; this.nationality = nationality; } } const me = new Human("darren", "korea"); //인스턴스 생성 console.log(me);

constructor는 python으로 치자면 __init__ 같은 것.

또한, 새 인스턴스를 생성할 때 new를 붙여주는 것을 잊지 말아라.

한편 React에서 class를 사용할 때 extends React.component를 했던 것처럼 확장이 가능하다.

class Human { constructor(name, nationality) { this.name = name; this.nationality = nationality; } sayName() { console.log(`My Name is ${this.name}`); } } class Baby extends Human { cry() { console.log("waaaaaa"); } } const phony = new Baby("dora", "korea"); phony.cry(); phony.sayName();

from http://darrengwon.tistory.com/159 by ccl(A) rewrite - 2020-03-17 00:54:13

댓글

이 블로그의 인기 게시물

[React] - 18) 프로젝트 빌드하기(+코드 스플리팅)

입트영(2020.03.23) - Iced Drinks / 아이스 음료

Redux + React