prototype : 프로토타입
- 객체를 만드는 원형
- 함수도 객체이고, 객체인 함수가 기본으로 갖고 있는 프로퍼티
- 함수의 객체가 생성될 때 모든 객체가 공유하는 공간
- 자바의 static 개념
prototype에 멤버 정의
- 멤버를 함수 외부에 선언
- 여러 객체가 공유하게 하는 방법
prototype 사용 시 이점
- 생성자 함수 이용해서 객체 생성 시, 프로퍼티와 메서드는 객체마다 생성됨 -> 사용하지 않을 경우에도 생성되기 때문에 메모리 낭비
- 프로퍼티와 메서드를 미리 만들어 놓지 않고 필요 시 추가한 후 모든 객체에서 공유 -> 메모리 낭비를 줄일 수 있음
예제
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Javascript </title>
<script type="text/javascript">
function People() {
this.age = 20;
}
// 객체 생성
var person1 = new People();
var person2 = new People();
var person3 = new People();
// person1에 메서드 추가
person1.setAge = function() {
this.age += 10;
}
// prototype 프로퍼티에 setAge() 메서드 정의
People.prototype.setAge = function() {
this.age += 1;
}
// prototype 프로퍼티에 getAge() 메서드 정의
People.prototype.getAge = function() {
return this.age;
}
person1.setAge(); // person1.setAge() 호출
person2.setAge(); // People.prototype.setAge() 호출
person3.setAge(); // People.prototype.setAge() 호출
console.log(person1.age);
console.log(person2.age);
console.log(person3.age);
// People.prototype.getAge() 호출
console.log(person1.getAge());
console.log(person2.getAge());
console.log(person3.getAge());
</script>
</head>
<body>
</body>
</html>
'Frontend > Javascript' 카테고리의 다른 글
응용 예제 : 음성 녹음 (0) | 2021.12.15 |
---|---|
자바스크립트 객체 JSON 변환 (0) | 2021.12.13 |
사용자 정의 객체 (0) | 2021.12.13 |
폼 유효성 확인 예제 (0) | 2021.12.13 |
form 객체 (0) | 2021.12.10 |