命名空间动态加载的javascript文件的内容 [英] Namespace a dynamically loaded javascript file's contents
问题描述
是否可以命名动态插入的JavaScript文件?
Is it possible to namespace a JavaScript file inserted dynamically?
我知道我可以通过创建一个脚本
标签动态地包含一个JavaScript文件并将其插入到DOM中,但是这个包含文件可以命名空间吗?所以,如果文件有一个名为 bar
的函数,我希望通过命名空间访问它,比如 foo
:即 foo.bar()
。
I know that I can dynamically include a JavaScript file by creating a script
tag and insert it into the DOM, but can this included file be namespaced? So, if the file has a function called bar
, I would want access it through a namespace, say foo
: i.e. foo.bar()
.
推荐答案
是的, CommonJS Modules / 1.1 仅指定了一种方法。
Yes, CommonJS Modules/1.1 specifies only one way of doing it.
我只在服务器端使用Node.js,但我相信还有其他库可以使用兼容CommonJS的浏览器。请注意,服务器/浏览器有多个模块规范(尚未深入研究)。
I've used it only with Node.js on server side, but I believe there are other libraries created to work with browser that are CommonJS compliant. Beware that there are multiple module specifications for server/browser (didn't dig into that yet).
模块的编写方式与任何其他javascript一样,是唯一的补充你是否导出了你要公开的内容:
Modules are written just like any other piece of javascript, the only addition is you export what you want to expose:
module.exports.bar = Bar;
function Bar() {
// code
}
用法:
var foo = require('mymodule');
foo.bar();
在后台实际完成的是,整个代码被包装到另一个函数中,导出是它的属性。
What is actually done in the background, the whole code is wrapped into another function and exports are its properties.
此外, Michael Bolin在他关于JSConf的'with'关键字的讨论中谈到了类似的问题。
这篇关于命名空间动态加载的javascript文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!