使用 JavaScript 的原型方法访问构造函数中的变量?

javascriptweb developmentobject oriented programming更新于 2025/11/11 1:48:17

为此,请使用"原型"。JavaScript 对象从原型继承属性和方法。为了访问变量,我们还使用了 JavaScript 中的"this"。

示例

function Customer(fullName){
   this.fullName=fullName;
}
Customer.prototype.setFullName = function(newFullName){
   this.fullName=newFullName;
}
var customer=new Customer("John Smith");
console.log("Using Simple Method = "+ customer.fullName);
customer.setFullName("David Miller");
console.log("Using Prototype Method = "+customer.fullName);

要运行上述程序,您需要使用以下命令 −

node fileName.js。

这里,我的文件名是 demo79.js。

输出

这将产生以下输出 −

PS C:\Users\Amit\JavaScript-code> node demo79.js
Using Simple Method = John Smith
Using Prototype Method = David Miller

相关文章


有用资源