类中函数前的"get"关键字是什么 - JavaScript?

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/15 10:20:17

get 关键字可以用作 C#、Java 和其他技术的 getter 函数。

我们在类 − 中设置一个带有 get 的函数,如下所示

class Employee {
   constructor(name) {
   this.name = name;
   }
   get fullName() {
      return this.name;
   }
}

示例

以下是显示 get 示例的代码 −

class Employee {
   constructor(name) {
      this.name = name;
   }
   get fullName() {
      return this.name;
   }
}
var employeeObject = new Employee("David Miller");
console.log(employeeObject.fullName);

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

node fileName.js.

这里,文件名是 demo299.js。

输出

这将在控制台上产生以下输出 −

PS C:\Users\Amit\javascript-code> node demo299.js
David Miller

相关文章


有用资源