【问题标题】:Making a node.js module that either takes an argument or doesn't, and returns an appropriate function/object制作一个带参数或不带参数的 node.js 模块,并返回适当的函数/对象
【发布时间】:2014-05-14 18:51:01
【问题描述】:

我不确定这是否可能,但我仍然会问是否可能。

我想制作一个可以以两种方式之一使用的模块:

  1. 像这样:

    MyModule = require('mymodule');
    MyModule.do('stuff');
    模块输出东西
  2. 或者像这样:(使用附加参数调用)

    MyModule = require('mymodule')('some');
    MyModule.do('stuff');
    模块输出“一些”东西

我试着让它如此喜欢

函数 MyModuleThatDoesntTakeArguments(argument){
    函数 MyModuleThatTakesArgument(){
        this.argument = 参数;
    }
    // 这将在传递参数时调用
    MyModuleThatTakesArgument.prototype.do = function(){
        console.log('输出',参数,'东西');
    }

    // this* 将在没有参数传递时被调用
    this.do = 函数(){
        console.log('输出东西');
    }

    返回 MyModuleThatTakesArgument;
}
// 或者 this* 将在没有参数时调用 ″ ″
MyModuleThatDoesntTakeArguments.prototype.do = MyModuleThatDoesntTakeArguments.do;

module.exports = MyModuleThatDoesntTakeArguments;

它在使用参数 (#1) 调用时有效,但会出现“函数对象没有方法 do”之类的错误。

我意识到基本问题是它可以作为构造函数调用(当使用参数调用时(#1)),这使得它返回内部函数。但是当没有参数调用时(#2)它只是返回构造函数本身,不幸的是它不能调用它的方法(this.do.prototype.do),因此会给出该错误。

所以我猜我写的乳清是不可能的。

还有其他方法可以实现我想要的吗?

【问题讨论】:

  • 只需将 do 函数附加到函数本身而不是原型(并阅读一些关于 JS 中的原型如何工作的内容)。

标签: javascript node.js node-modules


【解决方案1】:

您还需要使用do 方法将构造函数设为“实例”。假设您希望它是一个构造函数(构造具有公共原型的对象),该模式可能如下所示:

function MyConstructor(prefix) {
    this.pref = prefix ? prefix + " " : "";
}
MyConstructor.prototype.do = function(str) {
    console.log(this.pref + str);
}

// now make it an "instance":
MyConstructor.call(MyConstructor, "");
utils.merge(MyConstructor.prototype, MyConstructor);

module.exports = MyConstructor;

现在你可以调用它了

var mod = new MyConstructor("some");
mod.do("stuff");

var mod = MyConstructor
mod.do("stuff");

您可以为工厂制作类似的东西。请注意,如果您想插入if (!(this instanceof MyConstructor) return new MyConstructor(prefix); 使其在没有new 的情况下工作,而不是使用MyConstructor.call(MyConstructor, ""); 初始化“实例”,您将需要手动执行MyConstructor.pref = "";

【讨论】:

    【解决方案2】:

    请记住,函数是 JavaScript 中的对象。可以给函数对象添加do方法!

    function MyModule(initParam)
    {
        this.initParam = initParam;
    }
    
    MyModule.do = MyModule.prototype.do = function(arg)
    {
        if(this instanceof MyModule)
            console.log(this.initParam + " " + arg);
        else
            console.log(arg);
    }
    
    module.exports = MyModule;
    

    【讨论】:

      猜你喜欢
      • 2016-03-04
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      • 2023-01-04
      相关资源
      最近更新 更多