Javascript 重构 - 实现 ES6 的优雅方式 类
Javascript Refactoring - Elegant ways to implement ES6 classes
我正在重构我的项目类。我不是 JS 专家,这就是为什么我在这里向使用这种语言的更有经验的程序员提问。
直到知道我正在这样做:
class Person {
// Constructor
constructor(name) {
Object.asign(this, {
name,
})
}
// Getters
get name() {
return this.name;
}
}
// Main class methods
Person.prototype.sayHello = function() {
console.log("Hello world");
}
...
但是当我这样做时:
const person = new Person("alex");
console.log(person.name); // This works... but...
我的代码编辑器 (VS Code) 没有检测到对象人物的 属性“名字”。相反,如果我这样做:
// Getters
getName() {
return this.name;
}
...
console.log(person.getName());
代码编辑器自动完成,检测对象的 getName() 方法。
在构造函数中使用 Object.assign 时会发生同样的事情。如果我这样做,我的编辑器只会检测成员 this.name = name...
此外,我不知道我是否可以将所有主要方法附加到原型...
我记得(也许我错了)使用函数式 类,你这样做的性能更好,避免了在创建新实例时重新创建方法。
有什么想法吗?谢谢。
您的 getter 正在返回 getter,而不是一些内部值。
class Person {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
}
const person = new Person('Victor');
console.log(person.name); // Victor
我正在重构我的项目类。我不是 JS 专家,这就是为什么我在这里向使用这种语言的更有经验的程序员提问。
直到知道我正在这样做:
class Person {
// Constructor
constructor(name) {
Object.asign(this, {
name,
})
}
// Getters
get name() {
return this.name;
}
}
// Main class methods
Person.prototype.sayHello = function() {
console.log("Hello world");
}
...
但是当我这样做时:
const person = new Person("alex");
console.log(person.name); // This works... but...
我的代码编辑器 (VS Code) 没有检测到对象人物的 属性“名字”。相反,如果我这样做:
// Getters
getName() {
return this.name;
}
...
console.log(person.getName());
代码编辑器自动完成,检测对象的 getName() 方法。
在构造函数中使用 Object.assign 时会发生同样的事情。如果我这样做,我的编辑器只会检测成员 this.name = name...
此外,我不知道我是否可以将所有主要方法附加到原型...
我记得(也许我错了)使用函数式 类,你这样做的性能更好,避免了在创建新实例时重新创建方法。
有什么想法吗?谢谢。
您的 getter 正在返回 getter,而不是一些内部值。
class Person {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
}
const person = new Person('Victor');
console.log(person.name); // Victor