简体   繁体   中英

ES6 function with no parameters?

Is there a way to make a function that is being called with no parameters ? for example, I have this class

export class Student {
  constructor(ssn) {
    this.SSN = ssn;
  }
  SocialSecurityNumber() {
    return this.SSN;
  }
}

I want to be able to do this:

let student = new Student(123456);
console.log(student.SocialSecurityNumber);

this doesnt work now, but is there a syntax that I can use to accomplish this ?

Just to add that an alternative to calling the function with parenthesis student.socialSecurityNumber() , you could make this a getter:

 class Student { constructor(ssn) { this.SSN = ssn; } get socialSecurityNumber() { return this.SSN; } } const student = new Student(123456); console.log(student.socialSecurityNumber); 

That way you could call it with the same syntax as a property.

If you are supporting Object methods, you can add object properties similar to the syntactic sugar you'd see in C#.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Basically,

Object.defineProperty(this, 
                      'SocialSecurityNumber',
                      {
                          get: function() { return this.SocialSecurityNumber(); }
                      }

inside your constructor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM