向ES6类动态添加函数的正确方法 [英] Proper way to dynamically add functions to ES6 classes

查看:779
本文介绍了向ES6类动态添加函数的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的类,只有一个方法 exec(arg1,..,argn)我希望有一些调用<$ c $的别名方法c> exec 带有预定义的参数值(例如 exec_sync = exec.bind(this,true))。

I have a simple class with a single method exec(arg1,..,argn) and I want to have a number of alias methods which call exec with predefined argument values (e.g. exec_sync = exec.bind(this, true)).

以下是诀窍:

class Executor {
  constructor() {
    this.exec_sync = this.exec.bind(this, true);
  }

  exec(sync, cmd, args/* ... */) {
    // impl
  }
}

但是我不知道这是不是一个好主意,或者这是不是惯用的ES6。

But I don't know if this is a good idea or if this is idiomatic to ES6.

UDATE:

在现实生活中,我有两个嵌套循环分别有3个和4个循环,用于动态地向类中添加12个别名方法。当你真正可以利用JS作为基于原型的编程语言时,明确定义别名方法将是一项繁琐的任务。

In a real-life example I have two nested loops with respectively 3 and 4 loops, which are used to dynamically add a total number of 12 alias methods to the class. It would be a cumbersome task to explicitly define the alias methods when you actually can take advantage of JS being a prototype-based programming language.

更新2 - 示例:

假设我们有一个简单的HTTP客户端,其方法为 request(方法,正文)我们想为 GET PUT 等提供别名方法。它看起来如下所示:

Suppose we have have a simple HTTP client with a method request(method, body) and we want to provide alias methods for GET, PUT, etc. It would look something like the following:

class HTTP {
  constructor() {
    ['GET', 'PUT', 'POST', 'DEL'].forEach((method) => {
      this[method] = this.request.bind(this, method);
    }, this);
  }

  request(method, body) {
    // execute the HTTP request
  }
}


推荐答案

你的解决方案很好,尽管在<$上创建所有这些方法会更好c $ c>原型级别:

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.

这篇关于向ES6类动态添加函数的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆