[TIL / JavaScript] prototype

Changyun Go·2022년 1월 7일
0
post-thumbnail

[TIL / JavaScript] prototype

객체의 쓸모


  • 객체라는 디렉토리에 연관된 변수와 함수를 정리 정돈할 수 있다.
var MyMath = {
    PI:Math.PI,
    random:function(){
        return Math.random();
    },
    floor:function(val){
        return Math.floor(val);
    }
}

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:10,
    sum:function(){
        return this.first+this.second+this.third;
    }
}
console.log("kim.sum()", kim.sum()); // kim.sum 60
console.log("lee.sum()", lee.sum()); // kim.sum 30

객체를 하나씩 수동으로 만들어내고 항목을 수정하려 하면 같은 취지의 객체를 모두를 수정해야 했다.

var d1 = new Date('2019-4-10');
console.log('d1.getFullYear()', d1.getFullYear()); // 2019
console.log('d1.getMonth()', d1.getMonth()); // 3

우리가 Date를 사용할 때 new를 항상 붙여줬고, Date의 내부 설계를 모르지만 사용할 수 있었다. → new라는 생성자를 통해 객체를 만들어서 리턴하는 것이다.

function Person(name, first, second, third){
    this.name=name;
    this.first=first;
    this.second=second;
		this.third=third;
    this.sum = function(){
        return this.first+this.second+this.third;
    }
}
 
var kim = new Person('kim', 10, 20, 30);
var lee = new Person('lee', 10, 10, 30);
console.log("kim.sum()", kim.sum()); // 60
console.log("lee.sum()", lee.sum()); // 30

그냥 Person을 호출하면 그냥 함수일 뿐이기에 리턴하지 않으면 결괏값이 없지만, new를 붙이면 객체를 생성하는 생성자 함수가 된다.

  1. 객체를 만든다.
  2. 객체의 초기 상태를 세팅한다.

생성자 함수에 인자로 값을 넣어주면 손쉽게 객체를 생성하고 수정할 수 있다.

prototype


  • 우리말로 원형이라는 뜻을 가지고 있다.
  • 자바스크립트를 프로토타입 기반 언어라고도 한다.

생성자 함수 내부에 메소드를 만드는 것의 단점

  • 객체가 생성될 때마다 함수가 선언된다. → 컴퓨터 메모리가 낭비된다.
  • 많은 객체에서 해당 함수를 수정하려면 반복 작업이 필요하다.

하나의 생성자를 이용해서 만든 모든 객체가 공통적으로 사용할 수 있는 함수를 만들 수 있다.

function Person(name, first, second, third){
    this.name=name;
    this.first=first;
    this.second=second;   
}
 
Person.prototype.sum = function(){
    return 'prototype : '+(this.first+this.second);
}
 
var kim = new Person('kim', 10, 20);
kim.sum = function(){
    return 'this : '+(this.first+this.second);
}
var lee = new Person('lee', 10, 10);
console.log("kim.sum()", kim.sum()); // prototype : 30
console.log("lee.sum()", lee.sum()); // prototype : 20

prototype을 사용해서 Person이라는 생성자 함수에 공통적으로 사용할 sum이라는 메소드를 만들 수 있다.

  • 생성자 함수에 정의되지 않기 때문에 한 번만 실행할 수 있으며 쉽게 수정할 수 있다.
  • prototype을 기본으로 실행하지만, 원한다면 각 함수마다 별도로 정의해서 사용할 수도 있다.
    1. 해당 변수에 메소드가 있는지 찾는다.
    2. 있으면 실행 or 없으면 해당 변수의 생성자에 메소드가 있는지 찾는다.
  • 함수는 prototype을 사용하는 것이 일반적이며, 이외는 생성자 함수 내부에 넣는 게 일반적이다.

P.S.

✍️ 책으로 봤을 때는 생소하다는 느낌이 강했는데, 강의로 보니까 생각보다 어려운 개념은 아니었다🤔 실제 코드에 얼마나 잘 녹여내는지가 중요한 것 같다.

Reference


0개의 댓글