使用具有 JavaScript 原型方法的建構函式訪問變數?


為此,請使用“原型”。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

更新於:07-9 月-2020

821次檢視

開啟你的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.