JavaScript 物件 - prototype



JavaScript 物件的 prototype 屬性允許你向任何物件(Number、Boolean、String 和 Date 等)新增屬性和方法。

在 JavaScript 中,物件 prototype 屬性是一個全域性屬性,幾乎所有物件都可用。

語法

以下是 JavaScript 物件 prototype 屬性的語法:

object.prototype.name = value

這裡,name 可以是任何你想新增到物件的屬性方法名

引數

  • 它不接受任何引數。

返回值

此屬性沒有返回值。

示例 1

使用 prototype 屬性向物件新增屬性

在下面的示例中,我們使用 JavaScript 物件 prototype 屬性向名為 "student" 的物件新增名為 "city" 的屬性。

<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script>
   function student(name, age){
      this.name = name;
      this.age = age;
   }
   const obj = new student("Rahul Verma", 22);
   //using prototype property to set a property
   document.write("Before adding the city property: ", obj.city);
   String.prototype.city = null;
   obj.city = "Lucknow";
   document.write("<br>Name: ", obj.name);
   document.write("<br>Age: ", obj.age);
   document.write("<br>After adding City: ", obj.city);
</script>
</body>
</html>

輸出

上面的程式將 city 屬性新增到物件。

Before adding the city property: undefined
Name: Rahul Verma
Age: 22
After adding City: Lucknow

示例 2

使用 prototype 屬性向物件新增方法

以下是另一個使用 JavaScript 物件 prototype 屬性的示例。透過使用此屬性,我們向物件添加了兩個名為 "display()" 和 "editCredential()" 的方法。"display()" 方法顯示管理員憑據,而 "editCredential()" 方法允許編輯管理員憑據。

<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script>
   function Admin(){
      this.username = "xyz@gmail.com";
      this.password = "abc@123";
   }
   //adding display function using prototype
   Admin.prototype.display = function(){
      document.write("Username: ", this.username, ", Password: ", this.password);
   }
   //adding editCredential function using prototype
   Admin.prototype.editCredential = function(username, password){
      this.username = username;
      this.password = password;
   }
   const a = new Admin();//calling the object using the Admin() class
   document.write("Admin Credential before edit:<br>");
   a.display();
   a.editCredential("admin12@gmail.com", "admin123");
   document.write("<br>Admin Credential after edit:<br>");
   a.display();
</script>
</body>
</html>

輸出

執行上述程式後,將顯示以下結果:

Admin Credential before edit:
Username: xyz@gmail.com, Password: abc@123
Admin Credential after edit:
Username: admin12@gmail.com, Password: admin123
廣告