1 minute read

프로토타입과 클래스

*객체 생성자- 함수를 통해서 객체를 생성해주고, 객체만의 함수를 만듦

function Animal(type,name,sound){
    this.type=type;
    this.name=name;
    this.sound=sound;
    this.say=function(){
        console.log(this.sound);
    }
}

const dog=new Animal('dog','멍멍이','멍멍!');

위의 예시처럼, 자바스크립트에서 객체 생성자는 객체의 멤버변수를 매개변수로 적어주고, this(클래스 자기자신. 객체 자기자신) 를 이용하여 필드값을 설정해주고, 함수 또한 설정이 가능하다

그 후에는

const dog=new Animal(‘dog’,’멍멍이’,’멍멍!’);

와 같이 new 생성자를 이용하여 사용할 수 있다!

⚠️객체 생성자의 첫 문자는 대문자로! && 객체를 생성할 때에는 new 생성자를 이용해서 만들기!

⚠️위의 방식은 값은 다르지만, 틀은 같아서 약간은 비효율적! ▶️ 재사용성을 위한 프로토타입을 이용!

프로토타입

  • 객체생성자로 만들어진 객체들끼리 어떤 값이나 함수를 공유해서 사용할 수 있도록 하는 일종의 틀!

프로토타입은 객체생성자 명을 이용해서

Animal.prototype.필드명=~

으로 작성하면 된다!

function Animal(type,name,sound){
    this.type=type;
    this.name=name;
    this.sound=sound;
}

**📌Animal.prototype.say=function(){📌**
    console.log(this.sound);
}

const dog=new Animal('dog','멍멍이','멍멍!');
const cat=new Animal('cat','야옹이','야옹!');

dog.say();
cat.say();

프로토타입의 장점은 생성자 안에 정의되지 않은 함수나 변수더라도, 추가하여 해당되는 모든 객체에 대해서 적용할 수 있다는 점!

Animal.prototype.sharedValue=1;  
dog에 대해서도, cat에 대해서도 적용될  있음!

객체 생성자 상속하기

(뒤에 나올 클래스 개념을 안배웠다는 가정 하에서)

자바에서는 extends 를 이용해서 상속할 수 있었는데,

자바스크립트에서는

function 자식객체(필드){
	부모객체생성자.call(this[,
			자식에는 없는데 부모에는 있는 필드가 있다면 기입],
			필드);
}
//공통적인 프로토타입이 있다면
자식객체.prototype=부모객체.prototype;

와 같이 사용할 수 있다!

즉,

function Animal(type,name,sound){
    this.type=type;
    this.name=name;
    this.sound=sound;
}

Animal.prototype.say=function(){
    console.log(this.sound);
}

function Dog(name,sound){
    Animal.call(this,'',name,sound);
}

function Cat(name,sound){
    Animal.call(this,'고양이',name,sound);
}

Dog.prototype=Animal.prototype;
Cat.prototype=Animal.prototype;

const dog=new Dog('멍멍이','멍멍!');
const cat=new Cat('야옹이','야옹!');

dog.say();
cat.say();

와 같이 생각해볼 수 있다!


ES6에서 등장한 개념, “클래스”

  • 클래스에는 크게 constructor(생성자)와 함수가 존재하고
  • 함수는 자동으로 프로토타입으로 등록되어있다!
class Animal{
    constructor(type,name,sound){
        this.type=type;
        this.name=name;
        this.sound=sound;
    }
    //함수를 만들면 자동으로 프로토타입으로 등록됨
    say(){
        console.log(this.sound);
    }
}

const dog = new Animal('','멍멍이','멍멍!');
const cat = new Animal('고양이','야옹이','야옹');

dog.say();
cat.say();
console.log(Animal.prototype.say);
/*
ƒ say(){
        console.log(this.sound);
    }
*/
  • 이렇게 함수가 자동으로 프로토타입으로 등록되면, 상속할 때에 편하다!
  • 또한 클래스에서도 상속을 할 수 있는데 , 이때에는 extends와 super를 이용하여
class Dog extends Animal{
    constructor(name,sound){
        super('',name,sound);
    }
}

class Cat extends Animal{
    constructor(name,sound){
        super('고양이',name,sound);
    }
}

const dog1 = new Dog('멍멍이','멍멍!');
const cat1= new Cat('야옹이','야옹!');

dog1.say();
cat1.say();

와 같이 사용할 수 있는데, 사용방법은 자바와 유사하다!

Updated: