미미 공부/취미방

Javascrip 객체 지향 프로그래밍 : 프로토타입, 클래스 본문

to FED

Javascrip 객체 지향 프로그래밍 : 프로토타입, 클래스

mionager 2022. 9. 20. 15:58

프로토타입


프로토타입을 사용하는 이유

생성자 함수(Constructor Function)로 여러 개의 객체를 찍어낼 때,

생성자 함수가 가지고 있는 모든 값, 메서드를

모든 객체에 똑같이 계속 찍어내므로 메모리를 차지하게 된다.

그래서 한 번만 적어 놓고, 해당 생성자 함수로 만들어진 객체가 가져다 쓸 수 있게 한다.

function Person () {
    this.name = 'kim',
    this.first = 10,
    this.second = 20
}

var park = new Person();
var lee = new Person();
// Park과 Lee는 Person에 들어가 있는 동일한 내용을 각 각 가지고 있다.

 

 

원형(prototype) 지정하기

생성자함수명.prototype.key = 값;

아무것도 지정하지 않으면 undefined

Person.prototype.name = 'kim';
Person.prototype.first = 15;
Person.prototype.second = 30;

 

 

해당 생성자 함수로 만들어진 객체

해당 생성자 함수의 값을 똑같이 가지고 있다.

var choi = new Person();
console.log(choi.name);
console.log(choi.first);
console.log(choi.second);
//결과. kim, 15, 30

 

 

값을 수정하자

'choi'씨가 'kim'이라는 이름을 가지고 있는 건 말이 안 되니

name을 수정하려고 한다면 아래 코드처럼 덮어쓰면 된다.

CSS 스타일을 주는 것 처럼 부모의 값을 덮어쓴 값이 해당 객체 속성의 값이 되고,

값이 없으면 부모가 가지고 있는 값을 가져온다.

choi.name = 'choi';
console.log(choi.name);
// 결과. choi

 

 

 

클래스


클래스가 하는 일

1. 생성자 함수 처럼 객체를 만든다.

2. 생성자 함수 처럼 기본값을 설정한다.

(예. Person.prototype.name = 'kim')

3. 상속(혹은 확장)이 가능하다.

※ECMA6에 새로 나온 문법으로 구버전의 ECMA에서는 동작하지 않는다.

 

 

생성자 함수 vs 클래스 문법 비교

//생성자 함수
function Person (name, first, second) {
    this.name = name;
    this.first = first;
    this.second = second;
    this.sum = function() {
        return this.first + this.second;
    }
}
//혹은
Person.prototype.sum = function() {
	return this.first + this.second;
}
var kim = new Person('kim', 10, 40);
console.log(kim.sum()); // 결과. 50


//클래스
Person {
    constructor(name, first, second) {
        this.name = name;
        this.first = first;
        this.second = second;
    }
    sum() {
    	return this.first + this.second;
    }
}
var kim = new Person('kim', 10, 40);
console.log(kim.sum()); // 결과. 50

※constructor는 객체가 생성되기 시작할 때 실행된다. (왜 그런지/일반 메서드와 차이가 무엇인지 모르겠다.)

 

 

상속/확장이 왜 필요한가?

1. 다른 사람의 코드를 건들 수 없는데 그 사람이 쓴 코드+내 코드가 필요하다.

2. 기존 클래스에 소수의 객체를 위해서 메서드를 추가하고 싶다.

위의 경우 외에도 다양한 경우가 있겠지만 동일한 이유는, 원본 클래스 내용 + a 를 하고 싶을 때(원본 수정 없이)

class Person{
    constructor(name, first, second) {
    	this.name = name;
        this.first = first;
        this.second = second;
    }
    sum() {
    	return this.first + this.second;
    }
}

class PersonPlus extends Person{
    avg() {
    	return (this.first + this.second) / 2;
    }
}

var kim = new PersonPlus('kim', 10, 30);
console.log(kim.sum()); //부모인 Person에 있는 메서드
console.log(kim.avg()); //자식인 PersonPlus에 있는 메서드

PersonPlus는 자식, Person은 부모라고 할 수 있다.

class PersonPlus는 Person이 extends 된 것이고 Person의 모든 속성을 상속받는다.

 

 

부모 코드 내용에 약간 추가할 때는 'super'

부모 코드를 똑같이 쓰고 추가 사항을 적는다면 결국 똑같은 코드를 다시 적어야해서

상속/확장의 기능이 무의미해지는데,

이런 상황을 위해 'super'가 사용된다.

 

 

'super'는 2 가지 형태로 사용된다.

1. super() - 부모의 constructor 코드를 가져온다.

class Parent {
	constructor(name, first, second) {
    	this.name = name;
        this.first = first;
        this.second = second;
        this.a = 'test';
        this.b = 'super';
        this.c = 'constructor';
    }
}

class Child extends Parent {
	constructor(name, first, second, third) {
    	// Parent의 constructor를 다 가져온다.
        // name,first,second 매개변수는 Parent constructor 내용에 들어간다.
        // super를 쓰지 않으면 Child constructor에는 third만 있다.
    	super(name, first, second);
        
        // third가 추가되었다.
        this.third = third;
    }
}

 

2. super.method() - 부모.메서드를 가져온다.

class Parent {
	constructor(name, first, second) {
    	this.name = name;
        this.first = first;
        this.second = second;
    }
    sum() {
    	return this.first + this.second;
    }
}

class Child extends Parent {
    constructor(name, first, second, third) {
    	super(name, first, second);
        this.third = third
    }
    
    avg() {
    	// Parent.sum을 가져온다.
    	return (super.sum() + this.third)/3
    }
}

 

 

 

 

참조 : https://opentutorials.org/module/4047/24602

 

실습준비 - JavaScript 객체 지향 프로그래밍

수업소개 이 수업은 순수한 JavaScript의 기능만을 이용합니다. 따라서 웹브라우저나 Nodejs와 같은 JavaScript 실행환경 모두에서 동작합니다. 실습환경을 구축하는 방법을 소개합니다.  강의

opentutorials.org

 

Comments