我正在阅读有关 JavaScript 类的内容,并遇到了“公共类字段语法”这个术语。在深入研究它时,我遇到了这个Babel 的关于类属性的文档。
有人可以解释一下 -实现方面这种新语法的用例是什么? (它为 JavaScript 提供了哪些解决方案/好处,到目前为止还没有这些解决方案/好处?)
下面是一个示例(在 Google Chrome 中运行没有错误):
class Person {
firstName = "Mike";
lastName = "Patel";
// this is a public class field syntax
getName = () => {
return this.firstName + " " + this.lastName;
};
}
var p = new Person();
console.log(p.firstName); // Mike
console.log(p.lastName); // Patel
console.log(p.getName); // () => { return this.firstName + " " + this.lastName; }
console.log(typeof p.getName); // function
console.log(p.getName()); // Mike Patel