gpt4 book ai didi

javascript - ES6 函数没有参数?

转载 作者:行者123 更新时间:2023-11-29 16:40:46 28 4
gpt4 key购买 nike

有没有办法创建一个不带参数调用的函数?例如,我有这个类(class)

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

我希望能够做到这一点:

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

这现在不起作用,但是我可以使用一种语法来完成此任务吗?

最佳答案

只需添加使用括号student.socialSecurityNumber()调用函数的替代方法,您可以将其设为 setter/getter :

class Student {
constructor(ssn) {
this.SSN = ssn;
}
get socialSecurityNumber() {
return this.SSN;
}
}

const student = new Student(123456);
console.log(student.socialSecurityNumber);

这样您就可以使用与属性相同的语法来调用它。

关于javascript - ES6 函数没有参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46183056/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com