【问题标题】:How to prototype function in diferent context如何在不同的上下文中创建函数原型
【发布时间】:2017-09-09 12:19:53
【问题描述】:

我有一个函数,我将另外 2 个函数作为参数传递,例如:

doSomething(func1,func2)

我需要的是在导出函数时在其他上下文中对 func1 进行原型设计。

例如我有 2 个不同的文件:

在第一个中,我导出了一个接收 2 个参数函数的函数:

module.exports = (func1, func2) => {

}

在第二个中,我像 doSomething(func1,func2) 一样传递了我之前所说的参数

我怎样才能在 module.exports 中对 toString 进行原型化,这样我才能得到这样的 function1 输出:

/* func1() */ func2()

我试过这样:

module.exports = (func1, func2) => {

    func1.prototype.toString = function () {
        const comment = `/* ${(_.toString(func1))} */ \n`;
        return comment;
    };
};

结果是没有 /* */ 的 func1 对此有任何帮助?

【问题讨论】:

  • the result was 你是怎么得到这个结果的?
  • 是否要通过覆盖 toString 方法打印函数 1 代码?
  • 我想通过原型函数 1 在函数 1 中打印函数 2
  • 我认为“prototype”并不是指 JavaScript 中“prototype”通常所指的意思。

标签: javascript node.js ecmascript-6 lodash


【解决方案1】:

您可能想要定义func1.toString 而不是func1.prototype.toString。前者将用于func1.toString()。后者将用于func1instances,例如(new func1()).toString().

对象(包括函数)在文件/模块之间通过引用传递。在哪里执行此操作并不重要。

> Foo.prototype.toString = function () { return 'proto-tostring' }
> Foo.toString = function () { return 'ctor-tostring' }
> Foo.toString()
'ctor-tostring'
> (new Foo()).toString()
'proto-tostring'

【讨论】:

    猜你喜欢
    • 2019-05-06
    • 2016-12-02
    • 2012-12-13
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    • 2018-03-20
    相关资源
    最近更新 更多