JavaScript 对象 - prototype 属性
JavaScript 对象的 prototype 属性允许您向任何对象添加属性和方法(数字、布尔值、字符串和日期等)。
在 JavaScript 中,对象的 prototype 属性是一个全局属性,几乎所有对象都可用。
语法
以下是 JavaScript 对象 prototype 属性的语法 -
object.prototype.name = value
这里的 name 可以是任何您想要添加到对象的 属性 或任何 方法名称。
参数
- 它不接受任何参数。
返回值
此属性没有返回值。
示例 1
使用原型属性向对象添加属性。
在下面的示例中,我们使用 JavaScript 对象的 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);
//使用原型属性设置属性
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
使用原型属性向对象添加方法。
以下是另一个使用 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";
}
//使用原型添加显示功能
Admin.prototype.display = function(){
document.write("Username: ", this.username, ", Password: ", this.password);
}
//使用原型添加 editCredential 函数
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

