【问题标题】:Javascript Refactoring - Elegant ways to implement ES6 classesJavascript Refactoring - 优雅的方式来实现 ES6 类
【发布时间】: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


    【解决方案1】:

    你的 getter 返回的是 getter,而不是一些内部值。

    class Person {
        constructor(name) {
            this._name = name;
        }
    
        get name() {
            return this._name;
        }
    }
    const person = new Person('Victor');
    console.log(person.name); // Victor
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 2019-10-23
      • 2012-12-16
      • 2021-11-15
      • 2018-01-12
      • 2013-06-28
      • 2021-03-05
      • 2017-11-12
      相关资源
      最近更新 更多