TIL022 객체지향프로그래밍: Constructor & Prototype

Somi·2021년 5월 27일
0

JavaScript

목록 보기
18/27
post-thumbnail

1. Constructor

1) Cosntructor의 필요성

var kim = {
    name: 'kim',
    first: 10,
    second: 20,
    sum:function(){
        return this.first + this.second;
    }
}
var lee = {
    name: 'lee',
    first: 10,
    second: 10,
    sum:function(){
        return this.first + this.second;
    }
}

비슷한 구조의 객체를 동시에 수정하고 싶을 때, constructor가 없으면 아래와 같이 일일히 수정해줘야 한다... 이런 객체가 수억개가 있다면 매우 큰 품이 들 것. 그래서 등장한 것이 constructor!

var kim = {
    name: 'kim',
    first: 10,
    second: 20,
  	third: 30,
    sum:function(){
        return this.first + this.second + this.third;
    }
}
var lee = {
    name: 'lee',
    first: 10,
    second: 10,
  	third: 30,
    sum:function(){
        return this.first + this.second + this.third;
    }
}

2) Cosntructor의 사례

const d1 = new Date('2021-5-26');
console.log(d1.getFullYear())
console.log(d1.getMonth())
  • 내부적으로 2021-5-26이라는 데이터를 가진 객체가 생성되어 d1이 된다.
  • 객체에 대하여 getFullYear, getMonth라는 메소드를 실행

3) Constructor 만들기

  • 생성자 함수 : 객체의 초기상태를 설정해두고, 호출 시, 앞에 new 가 붙어 객체를 생성하는 함수
  • constructor를 쓰면, 코드가 간결해지며, 재사용성이 높아진다.
function Person(name, first, second, third){
    this.name = name,
    this.first = first,
    this.second = second,
    this.third = third,
    this.sum =function sum(){
        return this.first + this.second + this.third;
    }
}

const kim = new Person('kim', 10, 20, 30);
const lee = new Person('lee', 10, 10, 10);

console.log(kim);
console.log(lee.sum());

2. Prototype

JavaScript는 Prototype 기반의 언어이다!

1) Prototype의 필요성

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

위 객체에서 사용된 메소드를 수정하고 싶을 때, 해당 constructor에서 생성된 모든 객체들의 메소드를 아래와 같이 하나하나 바꿔줘야 한다.

kim.sum = function(){
    return 'modified : '+(this.first + this.second + this.third)
}

이렇게 하면 매우 비효율적이기 때문에 모든 객체가 공통적으로 사용되는 함수를 만들어줄 필요가 있다. 이때 사용되는게 Prototype!

즉, Prototype은 인스텐스가 사용할 수 있는 메소드를 저장하는 곳이다. 이는 객체가 생성될 때마다 해당 객체의 메소드를 만들어 메모리에 할당하는 대신, 생성자의 프로토타입에 정의함으로써 모든 객체들이 참조하여 사용할 수 있도록 하여 메모리를 효율적으로 사용할 수 있도록 한다.

2) Prototype 만들기

Person.prototype.sum =function (){
    return this.first + this.second + this.third;
}

console.log(kim.sum()); //60
console.log(lee.sum()); //30

3) Prototype의 활용

Prototype을 이용하면 인스턴스 각각의 메소드에 대한 수정이 필요할 때, 아래와 같이 오버라이딩 할 수 있는 장점이 있다!

kim.sum = function(){
    return 'this: ' + (this.first + this.second + this.third);
}

console.log(kim.sum()); //this: 60

0개의 댓글

관련 채용 정보