JavaScript Object prototype 属性允许您向任何对象(Number、Boolean、String 和 Date 等)添加属性和方法。
在 JavaScript 中,object prototype 属性是一个全局属性,几乎所有对象都可以使用。
语法
以下是 JavaScript Object prototype 属性的语法 -
object.prototype.name = value
在这里,名称可以是要添加到对象的任何属性或任何方法名称。
参数
它不接受任何参数。
返回值
此属性没有返回值。
示例 1
使用 prototype 属性向对象添加属性。
在下面的示例中,我们使用 JavaScript Object prototype 属性将名为“city”的属性添加到名为“student”的对象中。
<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
Name: Rahul Verma
Age: 22
After adding City: Lucknow
示例 2
使用 prototype 属性向对象添加方法。
以下是使用 JavaScript Object 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
Username: xyz@gmail.com, Password: abc@123
Admin Credential after edit:
Username: admin12@gmail.com, Password: admin123