【发布时间】:2020-12-07 05:16:43
【问题描述】:
我正在重构我的项目类。我不是 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) 没有检测到对象 person 的属性“名称”。相反,如果我这样做:
// Getters
getName() {
return this.name;
}
...
console.log(person.getName());
代码编辑器自动完成,检测对象的 getName() 方法。
在构造函数中使用 Object.assign 时也会发生同样的事情。如果我这样做,我的编辑器只会检测成员。name = name...
另外,我不知道将所有主要方法附加到原型上是否会很好......
我记得(也许我错了)使用函数类,你可以得到更好的性能,避免在创建新实例时重新创建方法。
有什么想法吗?谢谢。
【问题讨论】:
标签: javascript node.js performance oop refactoring