JavaScript 中函式原型


JavaScript 中建立的函式始終會擁有 JavaScript 引擎新增的原型屬性。原型屬性是一個物件,預設情況下包含建構函式屬性。可以透過以下方式訪問函式原型:-

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>

輸出

點選“單擊此處”按鈕 -

更新時間:2020 年 7 月 18 日

175 個瀏覽量

開啟你的 事業

透過完成課程取得認證

開始
廣告
© . All rights reserved.