且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

向ES6类动态添加函数的正确方法

更新时间:2022-06-15 08:55:24

你的解决方案很好,尽管在原型级别:

Your solution is fine, though it'll be better to create all those methods once on a prototype level:

['GET', 'PUT', 'POST', 'DEL'].forEach((method) => {
  Executor.prototype[method] = function (body) {
    return this.request(method, body)
  }
})

原型方法是稍微快一点,因为这段代码只执行一次,而每次创建新实例时都会执行构造函数。

prototype approach is slightly faster, because this code is executed only once, while constructor code is executed every time new instance is created.

prototype的另一个优点 over 构造函数是与类继承兼容的。所以,如果你以后扩展你的课程,即使你重新定义任何这些方法,也不会有任何破坏。

Another advantage of prototype over constructor is that its compatible with classes inheritance. So, if you'll extend your class later nothing will break even if you'll redefine any of those methods.

顺便说一句,你可以使用 require('http')。METHODS methods 而不是这里的HTTP动词的硬编码数组。

By the way, you can use require('http').METHODS or methods package instead of hard-coded array of HTTP verbs here.