使用ES2015,我想扩展Function
类并将其实例用作可调用函数。
class Foo extends Function {
// how to wite behavior?
}
let foo = new Foo();
foo();
foo.call();
// this is callable, but no behavior defined
如何foo
在其声明中让其具有特定行为?
该Function
构造函数接受参数:
new Function ([arg1[, arg2[, ...argN]],] functionBody)
在这种情况下,您将super
使用适当的参数进行调用:
// SNIPPET ONLY WORKS ON ES2015-ENABLED ENVIRONMENTS
"use strict";
class Foo extends Function {
constructor() {
super("a", "console.log(a);")
}
}
let foo = new Foo();
foo("one");
foo.call(null, "two");
现在,在字符串文字中编写JavaScript代码很痛苦,并且函数文本中的代码是在全局范围内进行评估的,因此我们无法执行类似在构造函数中定义实际函数并从函数文本中对其进行调用的操作。因此,这用途有限。但...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句