创建一个类,使用es6类语法创建Function对象作为实例 [英] Create a class that creates Function objects as instance using es6 class syntax

查看:393
本文介绍了创建一个类,使用es6类语法创建Function对象作为实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个实例化函数的类,它的原型方法?我试图将代码从原型结构转换为使用es6类语法。这里是一个设计和过分简化的起点示例

Is it possible to create a class that instantiates functions with methods on it's prototype? I am trying to convert code from prototype structure to using the es6 class syntax. Here is a contrived and over simplified example of the starting point

function createFun(init) {
  function fun(newDats) {
    this.data = newDats;
    // create universe
  }
  function internalMethod() {
  }
  fun.data = init;
  fun.aMethod = function () {
    internalMethod();
  }
  assign(fun, AnExtendableClass.prototype);
  return fun;
}

// and can be used as such
fun = createFun('first');
fun('second');
fun.aMethod();
fun.methodFromExtendableClass('third')

p>

And this is what I have tried

class Fun extend AnExtendableClass {
   constructor(init) {
     super();
     this.data = init;
     function fun(newDats) {
       this.data = newDatas;
       //create universe
     }
     assign(fun, this);
     return fun;
   }

   aMethod() {
   }
}


b $ b

不幸的是,这不工作,函数没有方法作为回报。

Unfortunately this does not work and function with no methods in return.

推荐答案


是否可以创建一个实例化函数的类, p>

Is it possible to create a class that instantiates functions with methods on it's prototype?

是的,使用ES6可以子类化 Function - 然而, nice,因为构造函数需要代码字符串:

Yes, with ES6 it is possible to subclass Function - however, that's not exactly nice, as the constructor expects code strings:

class Fun {
    constructor() {
        super("newDats", `
            this.data = newDats;
            // create universe
        `)
    }
    data() { }
    aMethod() { }
}

let fun = new Fun;
fun(…);
fun.aMethod(…);




我试图将代码从原型结构转换为使用es6类句法。这里是一个设计的和过分简化的起点示例

I am trying to convert code from prototype structure to using the es6 class syntax. Here is a contrived and over simplified example of the starting point

不要使用 class 语法。新的语法非常有限,只应该用于标准类声明。如果你做任何奇怪的事情 - 从构造函数返回函数,从其他类复制方法,分配静态属性和使用内部方法在这方面是绝对奇怪 - 然后去使用老,显式的方式。新的 Reflect.setPrototypeOf 在这里给你额外的自由。

Don't use the class syntax for that. The new syntax is very limited, and should only be used for standard class declarations. If you do anything weird - and returning functions from the constructor, copying methods from other classes, assigning static properties and using internal methods is definitely weird in this regard - then go use the "old", explicit way. The new Reflect.setPrototypeOf is giving you additional freedom here.

这篇关于创建一个类,使用es6类语法创建Function对象作为实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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