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.