Proper way to dynamically add functions to ES6 classes

北慕城南 提交于 2019-11-30 03:05:39

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.

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.

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

I don't know about this being idiomatic (since it's more about design, rather than programming language itself), but I personally think creating explicit functions would be better:

exec_sync(...args) {
    return this.exec(true, ...args); 
}

I like @leonid's answer, but is there a way to allow mangling when you using dynamic computed property names.

['VERYBIGNAME', 'VERYBIGNAME2', 'VERYBIGNAME3'].forEach((method) => {
   Executor.prototype[method] = function (body) {
     return this.request(method, body)
   }
})

in your minified and mangled javascript these VERYBIGNAME strings will exist.

so if I am able to get references to these VERYBIGNAME functions can I use something like

const references = { VERYBIGNAME1, VERYBIGNAME2, VERYBIGNAME3 };

Object.assign(Executor.prototype, { ...references });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!