<!DOCTYPE html>
<html>
<head>
<title>예제9-3프로토타입</title>
</head>
<body>
<h3>프로토타입</h3>
<script>
function Human(name, age, sex, speed) {
this.name = name;
this.age = age;
this.sex = sex;
this.speed = speed;
}
Human.prototype.walk = function() { this.speed = 5; }
Human.prototype.run = function() { this.speed += 3; }
var cmHuman = new Human("Park", 12, "male", 20);
var cfHuman = new Human("Kim", 12, "female", 15);
do {
document.write("Name:" + cmHuman.name + " run:" + cmHuman.speed + "<br />");
cmHuman.run();
document.write("Name:" + cfHuman.name + " run:" + cfHuman.speed + "<br />");
cfHuman.run();
} while (cmHuman.speed < 35);
cmHuman.walk();
cfHuman.walk();
document.write("Name:" + cmHuman.name + " walk:" + cmHuman.speed + "<br />");
document.write("Name:" + cfHuman.name + " walk:" + cfHuman.speed + "<br />");
</script>
</body>
</html>
function Human(name, age, sex, speed)는 새로운 객체를 생성하기 위한 생성자 함수입니다. new 키워드와 함께 호출하면 다음과 같은 과정이 실행됩니다:
this 키워드가 새로 생성된 객체를 가리키도록 바인딩됩니다.JavaScript의 모든 함수는 prototype 속성을 가집니다. 메서드를 생성자 함수 내부가 아닌 프로토타입 객체에 추가하는 이유는 메모리 절약 때문입니다.
| 구분 | 인스턴스 속성 (Instance Properties) | 프로토타입 메서드 (Prototype Methods) |
|---|---|---|
| 예시 | this.name, this.speed |
Human.prototype.walk, Human.prototype.run |
| 할당 방식 | 각 인스턴스마다 독자적인 메모리 공간에 저장됨 | 프로토타입 객체 메모리에 1개만 생성되어 모든 인스턴스가 공유함 |
| 장점 | 인스턴스별 독립적인 데이터 관리 가능 | 동일한 기능을 가지는 함수를 중복 생성하지 않아 메모리 절약 |
this 바인딩의 의미메서드 및 생성자 내부의 this는 호출 시점(Execution Context)에 해당 메서드를 실행한 객체 인스턴스를 참조합니다.
cmHuman.run() 실행 시: this.speed는 cmHuman.speed를 의미합니다.cfHuman.run() 실행 시: this.speed는 cfHuman.speed를 의미합니다.do...while)조건식 cmHuman.speed < 35에 따라 반복이 실행됩니다.