【问题标题】:Coffeescript require module with arguments, browserifyCoffeescript 需要带参数的模块,browserify
【发布时间】:2014-12-07 05:29:51
【问题描述】:

如果不检查我以前在 javascript 中的代码,我可以在 nodejs 应用程序中要求模块,如下所示:

app = require('./foo')('argstring')

我还没有检查我的任何代码库,但我当然记得我可以在 require 之后立即传递参数。

但我现在正在做客户端应用程序,并决定使用 browserify 来获得在客户端 js 应用程序中使用 require 的优势。 (这次我用的是coffeescript)

我有这样的课:

class Foo
  constructor: (@argstring) ->
  bar: () ->
    console.log @argstring

module.exports = Foo

现在我必须在我的主咖啡文件中使用它:

fap = require('./foo')('some string')
console.log fap // returns undefined

如果我这样做:

Foo = require('./foo')
fap = new Foo 'some string'
console.log fap // returns the object correctly

虽然我可以,显然选择使用实例化,但我不喜欢,因为它多了 1 个代码。

【问题讨论】:

    标签: javascript node.js coffeescript browserify


    【解决方案1】:

    foo = new (require('./foo'))('some string')

    您应该可以在一行上进行此实例化,您只需要确保并且实际上是new 对象,并调用正确的构造函数方法。

    【讨论】:

    • 我这样做并说,can't find module './foo',但这有效:new (require('./foo'))('some string) 你为什么这么认为?
    • 好问题,我不完全确定。如果没有括号,表达式执行的顺序可能不是我们所期望的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多