JavaScript로 생성된 함수에는 항상 JavaScriptengine에 의해 추가된 prototype 속성이 있습니다. 프로토타입 속성은 기본적으로 생성자 속성을 포함하는 객체입니다. 함수 프로토타입은 −
를 통해 액세스할 수 있습니다.functionName.prototype
함수 생성자를 사용하여 객체를 생성할 때 이 프로토타입 속성을 사용하여 해당 함수 생성자가 생성한 객체 간에 메서드 또는 속성을 공유할 수 있습니다.
다음은 JavaScript의 함수 프로토타입에 대한 코드입니다. -
예시
<!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;
color: blueviolet;
}
</style>
</head>
<body>
<h1>Function prototypes in JavaScript</h1>
<div class="result"></div>
<br />
<button class="Btn">Click Here</button>
<h3>Click on the above button to call the welcome method of person1 and person2 object</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
function personConstructor(fName, lName) {
this.fName = fName;
this.lName = lName;
}
personConstructor.prototype.welcome = function () {
return "Welcome " + this.fName + " " + this.lName;
};
let person1 = new personConstructor("Rohan", "Sharma");
let person2 = new personConstructor("Shawn", "Smith");
BtnEle.addEventListener("click", () => {
resEle.innerHTML = "person1.welcome() = " + person1.welcome() + "<br>";
resEle.innerHTML += "person2.welcome() = " + person2.welcome() + "<br>";
});
</script>
</body>
</html> 출력

'여기를 클릭' 버튼을 클릭하면 -
