JS Class

  • html 문서에서 속성으로 존재하는 클래스명: 공통 클래스명 부여가 가능(for CSS style)
  • 실생활에서 학교 : 클래스 단위로 수업을 받거나 움직임 (과목 또는 소풍)
  • 객체 영역 : 속성(key: value(특정 데이터))과 기능(key:value(function))

=> Class라는 존재는 어떠한 그룹을 가리킴

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const pony = {
name : "아반떼",
color : "white",
start : function() {
console.log(`${this.name}가(이) 시동을 검`);
this.drive();
},
drive : function() {
console.log(`${this.name}가(이) 주행을 함`);
this.stop();
},
stop : function() {
console.log(`${this.name}가(이) 멈춤`);
this.parking();
},
parking : function() {
console.log(`${this.name}가(이) 주차함`);
},
repairCenter : function() {
this.color = "빨간색";
console.log(`${this.name}가(이) ${this.color}으로 색상을 교체했습니다.`);
}
}

pony.start();
pony.repairCenter();

객체

  • 객체의 단점: 한번 선언된 객체는 재활용이 불가능
  • 객체를 재활용 가능한 형태로 구조화하여 구성하는 것이 필요 ==> 프로토타입(화) : 재상용과 재활용을 목적으로 만든 스크립트 코드

객체 속성의 일반적인 생성 - 1

1
2
3
4
5
6
7
const obj1 = {
name : "아이폰13"
}
obj1.color = "silver";
obj1["price"] = "1,500,000원";
console.log(obj1);
// {name: '아이폰13', color: 'silver', price: '1,500,000원'}

객체 속성의 일반적인 생성 - 2

1
2
3
4
5
6
const obj2 = new Object();
obj2.name = "갤럭시22 note";
obj2.color = "Metal Blue";
obj2["price"] = "1,500,000원";
console.log(obj2);
// {name: '갤럭시22 note', color: 'Metal Blue', price: '1,500,000원'}

프로토타입

  • 즉시 실행 함수: 함수를 호출하는 명칭은 없으나 함수를 시작할 수 있는 구조를 갖춘 함수 (제일 빠름)
  • 생성자(constructure): 객체 내의 어떤 새로운 key와 value값을 생성하여 객체가 받아들일 수 있도록 구성. 객체 내부의 어떤 생성을 담당하는 곳.
  • alt + 방향키
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const Car = (function(){
console.log("프로토 타입의 시작");

// 생성자
function Car(name1, color1, type1) {
console.log(this); // Car {} (객체 형태)
this.name = name1;
this.color = color1;
this.type = type1;
console.log(this); // Car {name: '아반떼', color: '레드', type: '준중형'}
}

// 프로토타입은 일종의 대기 상태로 구성
// start
Car.prototype.start = function() {
console.log(this); // Car {name: '아반떼', color: '레드', type: '준중형'}
console.log(`${this.color} ${this.name}가(이) 시동을 겁니다.`);
this.drive;
}

// drive
Car.prototype.drive = function() {
console.log(`${this.color} ${this.name}가(이) 주행을 합니다.`);
this.stop;
}

// stop
Car.prototype.stop = function() {
console.log(`${this.color} ${this.name}가(이) 주행을 멈춥니다.`);
this.parking;
}

// parking
Car.prototype.parking = function() {
console.log(`${this.color} ${this.name}가(이) 주차를 합니다.`);
}

return Car;
})();

const avante = new Car("아반떼", "레드", "준중형");
console.log(avante); // Car {name: '아반떼', color: '레드', type: '준중형'}
avante.start();

const tusan = new Car("투산", "블랙", "SUV");
tusan.start();
  • 학생 Student - 1 : 개별적으로 변수를 구성하여 각 학생의 결과값을 도출
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const Student = (function() {
// 생성자 파트
function Student(st_name, st_classNum) {
this.name = st_name;
this.classNum = st_classNum;
}

Student.prototype.enterance = function() {
console.log(`${this.name} 학생이 ${this.classNum}에 들어갔습니다.`);
}

return Student;
})();

const student1 = new Student("강하늘", "3반");
console.log(student1); // Student {name: '강하늘', classNum: '3반'}
console.log(student1.name); // 강하늘
student1.enterance(); // 강하늘 학생이 3반에 들어갔습니다.

const student2 = new Student("이하늘", "5반");
console.log(student2); // Student {name: '이하늘', classNum: '5반'}
console.log(student2.name); // 이하늘
student1.enterance(); // 이하늘 학생이 5반에 들어갔습니다.

[실습문제] 학생 Student - 2

배열 데이터를 전달하여 프로토 타입으로 결과값을 도출하시오.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const mem_student = [
["강나라", "7반"],
["나지영", "3반"],
["김성우", "1반"],
["김동현", "5반"],
["이상균", "2반"],
["한가람", "4반"],
["박보영", "3반"]
];
console.log(mem_student[3][0]); // "김동현"
// OOO 학생이 O반에 들어갔습니다.

const Student1 = (function() {
// 생성자 파트
function Student1(st_name, st_classNum) {
this.name = st_name;
this.classNum = st_classNum;
}

Student1.prototype.enterance = function() {
console.log(`${this.name} 학생이 ${this.classNum}에 들어갔습니다.`);
}

return Student1;
})();

// 생성자 데이터 전달
for(v of mem_student) {
// console.log(v);
const student3 = new Student1(v[0], v[1]);
// console.log(student3);
student3.enterance();
}

[실습문제2] 게임 입장 파트 (던전)

  • 배열 패턴 : {“이름”, “종족”, 레벨}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const gamer = [
{name: "불타는 용병", category: "오크", level: 53}, // 0번 인덱스
{name: "얼음 마법사", category: "휴먼", level: 32}, // 1번 인덱스
{name: "할리퀸", category: "하이엘프", level: 3}, // 2번 인덱스
{name: "냉혈 전사", category: "휴먼", level: 27}, // 3번 인덱스
{name: "도로위의 무법자", category: "다크엘프", level: 65}, // 4번 인덱스
{name: "3시간 직진중", category: "오크", level: 12} // 5번 인덱스
];

console.log(gamer[2].category); // 하이엘프
// 출력 예시, 콘솔창에 "홍길동(오크 - 23) 님이 입장하셨습니다." (6명)
// 반드시 프로토타입을 이용하여 결과를 표현할 것.

const Gamer1 = (function() {
// 생성자 파트
function Gamer1(player_name, player_category, player_level) {
this.name = player_name;
this.category = player_category;
this.level = player_level;
}

Gamer1.prototype.play = function() {
console.log(`${this.name}(${this.category} - ${this.level}) 님이 입장하셨습니다.`);
}

return Gamer1;
})();

for(v of gamer) {
const Gamer = new Gamer1(v.name, v.category, v.level);
Gamer.play();
}

for문

  • 반복문을 활용하여 데이터 전달
  • for문 (초기값; 조건식; 증감식) {…실행문…}
  1. 초기값 -> 2) 조건식 검사(true) -> 3) 실행문 -> 4) 증감식
1
2
3
4
5
for(i=0; i<gamer.length; i++) {
const myHero = new Gamer1(gamer[i].name. gamer[i].category, gamer[i].level);
console.log(myHero);
myHero.play();
}

for ~ in 문

for(i in 배열 데이터 변수명) {실행문}
i는 0부터 배열데이터의 마지막 인덱스까지 반복하여 가져오는 인덱스 번호를 가리킴

1
2
3
4
5
for(i in gamer) {
console.log(i); // 문자형 데이터이기 때문에 바로 연산 불가
const myHero = new Gamer1(gamer[i].name. gamer[i].category, gamer[i].level);
console.log(myHero);
myHero.play();

for ~ of 문

for(v of 배열데이터변수명){…실행문…}
v는 0번 인덱스부터 마지막 인덱스까지의 실제 데이터 가져온다.

1
2
3
4
5
for(v of gamer){
console.log(v);
const Gamer = new Gamer1(v.name, v.category, v.level);
Gamer.play();
}

foreach문

배열 데이터.foreach(function(v, i) {…실행문…})

1
2
3
4
5
6
gamer.forEach(function(v, i){
console.log(v); // 각 인덱스별로 접근하는 실제 데이터
console.log(i); // 각 인덱스 번호를 추출, 숫자 데이터
const Gamer = new Gamer1(v.name, v.category, v.level);
Gamer.play();
})

Class

  • ES6에서는 객체를 클래스화시킴(마치 기다리고 있다가 웹브라우저에 데이터값이 전달되면 하나의 메모리 공간을 별도로 차지하게 만듦)
  • 생성자: 클래스 내부에 객체를 생성
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class NewCar {
constructor(name1, color1) {
this.name = name1;
this.color = color1;
}

// 기능: 행동수칙을 지정
start() {
console.log(this);
console.log(`${this.color} ${this.name}가(이) 시동을 겁니다.`);
this.drive();
}

drive() {
console.log(`${this.color} ${this.name}가(이) 주행을 합니다.`);
this.stop();
}

stop() {
console.log(`${this.color} ${this.name}가(이) 주행을 멈춥니다.`);
this.parking();
}

parking() {
console.log(`${this.color} ${this.name}가(이) 주차를 합니다.`);
}
}

const newAvante = new NewCar("뉴 아반떼", "코드블루");
console.log(newAvante);
newAvante.start();

const newTusan = new NewCar("뉴 투산", "메탈 블랙");
console.log(newTusan);
newTusan.start();

[실습문제]

  • Class를 활용하여 콘솔창에 “장바구니에 담긴 물건은 곰인형입니다.” 출력 (이때 “곰인형”은 전달되어지는 데이터 값으로 넣을 것)
  • Class를 활용하여 콘솔창에 “장바구니에 담긴 물건은 레고입니다.” 출력 (이때 “레고”는 전달되어지는 데이터 값으로 넣을 것)
1
2
3
4
5
6
7
8
9
10
11
12
13
class product {
constructor(item) {
this.name = item;
}

cart() {
console.log(`장바구니에 담긴 물건은 ${this.name}입니다.`);
}
}
const doll = new product("곰인형");
doll.cart();
const toy = new product("레고");
toy.cart();

클래스 주의사항

  • class라는 개념은 hoisting이 적용되지 않는다. class 인자가 먼저 선언되고 관련된 호출문이 문서상 나중에 작성되어야 한다.
1
2
3
4
5
6
7
8
9
10
11
class CartBox {
constructor(item) {
this.myItem = item;
}

inBox() {
console.log(`장바구니 상품: ${this.myItem}`);
}
}
const gift = new CartBox("옥스포드 블록");
gift.inbox();
  • 실제 전달되어지는 생성자와 행동으로 이어질 수 있는 기능을 동일한 명칭으로 작성했을 때
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class CartBox1 {
    constructor(item) {
    this.item = item;
    }

    item() {
    console.log(`장바구니 상품: ${this.item}`);
    }
    }
    const gift = new CartBox1("옥스포드 블록");
    gift.item();

상속

  • 자바스크립트가 개별적인 문서로 각 HTML에 접근하다보니, 기하급수적으로 문서가 늘어나기 시작(단점)…prototype과 class 선언으로 재활용 가능
  • 만약, 동물원에 대한 프로그램을 구성한다면 토끼, 햄스터, 원숭이, 호랑이, … 등에게 먹이를 주었는지 또는 주지 않았는지에 대한 결과값을 얻고자 하는 프로그램
    • 클래스 인자(Zoo)를 통해서 상속를 시도(Rabbit, Monkey, Tiger)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Zoo {
// 생성자 파트
constructor(animalName, animallFood) {
this.name = animalName;
this.food = animallFood;
}

// 메서드 파트
feed() {
console.log(`${this.name}에게 ${this.food} 먹이를 주었습니다.`);
}
}

const animal = new Zoo("동물", "음식");
animal.feed();

// 상속(extends) :
class Rabbit extends Zoo {}
const rabbit = new Rabbit("토끼", "클로버");

console.log(rabbit); // Rabbit {name: '토끼', food: '클로버'}
rabbit.feed(); // 토끼에게 클로버 먹이를 주었습니다. (상속받은 Zoo의 feed() 메서드에서 콘솔창으로 출력을 진행)

class Monkey extends Zoo {
// 메서드 오버라이딩 : 기존 상속 받은 메서드에 "덮어쓰기"
// 자바에서는 @Override라는 문구로 이후에 작성

feed() {
console.log(`${this.name}는 감기에 걸려서 ${this.food}를 먹을 수가 없습니다.`);
}
}
const monkey = new Monkey("원숭이", "바나나");
console.log(monkey); // Monkey {name: '원숭이', food: '바나나'}
monkey.feed(); // 원숭이는 감기에 걸려서 바나나를 먹을 수가 없습니다.

class Tiger extends Zoo {}
const tiger = new Tiger("호랑이", "생닭");
console.log(tiger); // Tiger {name: '호랑이', food: '생닭'}
tiger.feed(); // 호랑이에게 생닭 먹이를 주었습니다.

실습문제

  • class + method override 적용

  • 각 캐릭터가 존재 + 각 캐릭터마다 장비가 달라요

  • knight (“기사”, “얼음검”)

  • wizard (“마법사”, “불의 지팡이”)

  • stealer (“도적”, “검은 단도”)

  • Dungeon 이라는 클래스 생성자와 기능인 action()을 넣어서 콘솔창에 “OOO이(가) OOO을(를) 사용했습니다.”

  • 메서드 오버라이드를 이용하여 콘솔창에 도적은 “OOO은 무기인 OOO을 버리고 도망갔습니다.”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Dungeon {
// 생성자 파트
constructor(fighter, weapon) {
this.name = fighter;
this.weapon = weapon;
}

// 메서드 파트
action() {
console.log(`${this.name}이(가) ${this.weapon}을(를) 사용했습니다.`);
}
}

// 상속(extends) :
class Knight extends Dungeon {}
const knight = new Knight("기사", "얼음검");
knight.action();

class Wizard extends Dungeon {}
const wizard = new Wizard("마법사", "불의 지팡이");
wizard.action();

class Stealer extends Dungeon {
constrouctor(fighter, weapon, cloths) {
super (fighter, weapon); // super라는 키워드를 통해서 부모 클래스의 생서앚를 호출
this.cloth = cloths; // 자식의 데이터를 받아서 속성을 추가
}
action() {
console.log(`${this.name}은(는) 무기인 ${this.weapon}와(과) ${this.cloth}을(를) 버리고 도망갔습니다.`);
}
}
const stealer = new Stealer("도적", "검은 단도", "검은 망토"); // 데이터 추가
stealer.action();

getter, setter

  • 편의점에서 삼각김밥과 햄버거를 구입하고자 한다.
  • 해당 제품, 가격, 수량
  • 수량은 최소 수량 1로 지정
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class CartMe {
constructor(name1, price1, number1) {
this.name = name1;
this.price = price1;
this.number = number1;

// settier 영역 - 1
set number (value) {
console.log(vaule); // -1
this._number = value < 1 ? 1 : value;
console.log(this._number); // this 제외하면 오류남
}

// getter 영역 - 2
get number() {
console.log(this._number); // 1
return this._number;
}

buy() {
console.log(`${this.price}원의 ${this.name}을(를) ${this.number}개 구입했습니다.`);
}
}
}

const hamberg = new CartMe("햄버거", 4000, -1);
hamberg.buy();

정적 메소드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Member2 {
constructor(id1, name1) {
this.id = id1;
this.name = name1;
}

// 정적 메서드
static test1() {
console.log(`${this.name}(${this.id})님 환영합니다.`);
}

// this는 안됨.
static test2(id, name) {
console.log(id); // kcm
console.log(name); // 김철민
console.log(`${name2}(${id2})님 환영합니다.`);
}
}
const mem2_1 = new Member2("hgd", "홍길동");
mem2_1.test(); // mem2)1.test1 is not a function
Member2.test1(); // Member2(undefined)님 환영합니다.
Member2.test2("kmc", "김철민"); // Member2(undefined)님 환영합니다.

REFERENCE
뷰(Vue.js) 프로그래밍 과정 _ 하이미디어 아카데미

  • © 2020-2025 404 Not Found
  • Powered by Hexo Theme Ayer