javascript - 如何在 JavaScript 中定义实例化函数的行为

标签 javascript

使用 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 构造函数 accepts arguments :

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 代码是一件痛苦的事情,函数文本中的代码是在全局范围内计算的,因此我们不能做一些事情,比如在构造函数中定义实际函数并从函数文本。所以这个用处有限。但是……

关于javascript - 如何在 JavaScript 中定义实例化函数的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35722036/

相关文章:

javascript - 将鼠标悬停在链接上后 Mouseenter 失败

javascript - 将 PHP 添加到 HTML 文件后 JQuery 不工作

java - 将 JSONArray 作为 HTTP 实体返回

javascript - 我应该等待 document.onload 事件吗?

javascript - 在 Vuejs 中使用 indexOf 方法

javascript - Cordova 后退按钮事件从不触发

javascript - 使用 JavaScript 为 SQL 清理数据

javascript - 定位用户 javascript 返回默认地址

javascript - 循环遍历 firebase 数据

javascript - 在整个 html 页面上等待光标