如何扩展 JavaScript 对象/函数以在初始化后公开 API 方法?
我想创建一个像这样工作的 JavaScript 应用程序:
- 有一个名为
bm
的函数/命名空间。 - 一开始,bm 只是一个函数,它有一个名为
setup
的方法,因此有两种可能:调用bm()
或定义一些调用bm 的设置变量。设置(设置)
。 - 要使用该库并公开 API,
bm
必须首先通过调用以下函数进行初始化:bm(url, options)
。如果初始化成功,API 应该会公开,因此bm
现在有其他方法,例如bm.method1
、bm.method2
...
我不知道不知道这到底是如何可能的,所以我想听听任何想法、例子或建议。提前致谢。
I want to create a javascript application that works like this:
- Has a function/namespace called
bm
. - At the start bm is just a function that has a method called
setup
, so two things are possible: callingbm()
or defining some setup variables callingbm.setup(settings)
. - To use the library and expose the API
bm
has to be initialized first by calling the function:bm(url, options)
. If initialized succesfully, the API should be exposed sobm
now has additional methods likebm.method1
,bm.method2
,...
I don't know how exactly is this possible, so I would like to hear any ideas, examples or suggestions. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好处是函数是一流的对象,因此您可以向它们添加方法。然后,您的主实例创建函数只需要检查并确保其作为实例调用:
可以通过以下任何方式调用:
What's nice is functions are first-class objects, so you can add methods to them. Then your primary instance creating function just needs to check and make sure its called as an instance:
This can be called any of these ways:
也许像...
Maybe something like...
我在这里没有看到任何问题。您可能想向 bm() 添加一个回调函数,该函数在 API 初始化时调用,如下所示:
您可以像向普通对象添加函数一样向 bm 添加函数:
I don't see any problem here. You might want to add a callback function to the bm(), which is called when API is initialized, like this:
You can add functions to bm like to an ordinary object: