코드노트

자바스크립트 프로토타입 이해 본문

Code note/자바스크립트

자바스크립트 프로토타입 이해

코드노트 2022. 8. 26. 22:22

프로토타입(prototype) // 원형 // 사물의 원래의 모습!?

- 객체가 만들어지기 위해서 객체의 모태가 되는 원형

- 자바스크립트는 프로토타입 기반 언어라고 부르기도 한다. prototype based languge

- 일반적인 객체 생성 방식: 속성은 생성자, 메서드는 프로토타입에서 정의

 

// 생성자 속성 정의
function Person(name, age) {
  this.name = name;
  this.age = age;
}
// prototype을 이용한 Person 메서드 정의
Person.prototype.isAudlt = function () {
  return this.age > 18;
};
Person.prototype.isChild = function () {
  return this.age < 12;
};

// 객체 생성
const p1 = new Person("bob", 26);
const p2 = new Person("alice", 15);

- 생성자 함수 내에는 메서드를 사용하지 않아야한다.

- 메서드 정의를 생성자 함수 밖에서 Person.prototype.메서드 를 정의하게 되면 생성자함수를 사용할 때마다 실행이 되지 않는다.

- 메서드 함수를 수정할 때에도 성능은 올리고 메모리는 줄일 수 있다.

 


 

// 생성자 속성 정의
function Person(name, first, second) {
  this.name = name;
  this.first = first;
  this.second = second;
}
// prototype을 이용한 Person 메서드 정의
Person.prototype.sum = function () {
  return "prototype : " + (this.first + this.second);
};

// 객체 생성
let kim = new Person("kwon", 10, 20);
let lee = new Person("lee", 10, 10);

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

- 만약 sum 함수를 통해서 kim이 가지고 있는 메소드만 다르게 동작을 하고 싶다면?

 

 

// 생성자 속성 정의
function Person(name, first, second) {
  this.name = name;
  this.first = first;
  this.second = second;
}
// prototype을 이용한 Person 메서드 정의
Person.prototype.sum = function () {
  return "prototype : " + (this.first + this.second);
};

// 객체 생성
let kim = new Person("kwon", 10, 20);
kim.sum = function() {
  return "this : " + (this.first + this.second);
}

let lee = new Person("lee", 10, 10);

console.log(kim); // this : 30
console.log(lee); // prototype : 20

- kim.sum을 통해서 특정 함수를 넣어주면 된다.

- 자바스크립트는 객체 자신이 속성을 가지고 있는지 먼저 찾게 된다. 그래서 kim.sum은 sum이라는 속성을 가지고 있기 때문에 kim은 this를 출력한다.

 


 

1. prototype 의미?

객체가 만들어지기 위해 객체의 모태가 되는 원형.

 

2. 생성자 함수 안에서 메서드 및 속성을 직접 정의하면 어떤 비효율이 나타나는가?

생성자 함수가 실행이 될 때마다 메서드가 계속 실행이 된다.

시간이 오래걸리고, 성능을 저하시키고, 메모리를 많이 차지하게 된다.

 

3. prototype를 통해서 어떻게 해결했는지?

생성자함수.prototype.메서드 =를 통해서 따로 객체를 생성해준다.