JavaScript 생성자 함수에 새로운 속성(property)이나 메서드(method)를 추가하려면 prototype 객체를 활용하면 됩니다. 생성자 함수의 프로토타입에 속성이나 메서드를 정의하면, 해당 생성자로부터 만들어진 모든 인스턴스가 이를 공유하여 사용할 수 있습니다. 이는 메모리를 효율적으로 관리할 수 있는 방법이기도 합니다.
예제 코드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>Add property,method to javaScript constructor</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to add property, method to constructor</h3>
<script>
let resEle = document.querySelector(".result");
function Human(firstName,lastName){
this.firstName = firstName;
this.lastName = lastName;
}
let obj = new Human('Rohan','Sharma');
document.querySelector(".Btn").addEventListener("click", () => {
Human.prototype.welcome = function(){
return 'Welcome '+this.firstName + ' ' + this.lastName;
}
Human.prototype.age = 22;
resEle.innerHTML = 'Adding property to constructor : age <br>' + obj.age + '<br>';
resEle.innerHTML += 'Adding function to constructor : welcome() <br>' +
obj.welcome() + '<br>';
});
</script>
</body>
</html>코드 설명
위 예제에서는 Human이라는 생성자 함수를 정의하고, firstName과 lastName 두 개의 속성을 초기화합니다. 그다음 버튼을 클릭하면 다음 작업이 수행됩니다.
Human.prototype.welcome— 프로토타입에welcome()메서드를 추가하여 이름과 성을 조합한 환영 메시지를 반환합니다.Human.prototype.age— 프로토타입에age속성을 추가하여 값 22를 설정합니다.
프로토타입에 추가된 속성과 메서드는 이미 생성된 인스턴스 obj에서도 즉시 접근할 수 있다는 점이 핵심입니다.
실행 결과
위 코드를 실행하면 다음과 같은 화면이 출력됩니다.

'CLICK HERE' 버튼을 클릭하면 아래와 같이 프로토타입에 추가된 속성과 메서드의 결과가 화면에 표시됩니다.