在CommonJS规范中概述的define()协议是什么? [英] What does the define() protocol outlined in CommonJS specification buy me?
问题描述
我了解诸如 正确的名称间距 和 模块模式 有关联的问题 渗透到全局范围 <强>。
我还完全看到在 require()
协议中提供的资源依赖关系管理的价值 CommonJS规范 。
然而,我不知道AMD define()
函数的用途和目的的好处。
strong>用于define的CommonJS签名为:
define );
另外...
- 我看到人 包装他们的模块
当
BOTH创建一个对象时,使用define()
全局范围。 - 包含正常模块的文件
模式插件也可以异步加载
。
首先,它似乎像另一个插件包装...直到我开始看到人们使用模块模式。 / p>
所以我的问题是:
- CommonJS规范中概述的
define()
协议
是什么?
购买我? -
-
- 是否代替模块化模式? >如果是,为什么?
//如果是的话,为什么?
require(foo.js,function(foo){
console.log(foo === 42); // true
});
//foo.js
/ *
define(42);
define({
foo:bar
});
define([bar.js],function(bar){
return bar.foo;
});
* /
define(function(){
return 42;
});
定义是一种不依靠全局范围传递模块化对象的好方法。
定义的特定API因库而异。
这里的基本思想是在文件中调用define定义该模块是什么。然后当你需要的文件,你得到的模块。
没有更快的速度(注入全局范围的速度较慢)。
使用 require
和 define
只有两个全局值。
上面的 define
示例匹配 requireJS API
I understand how things like proper name-spacing and the Module Pattern help issues associated with leaking into the global-scope.
I also completely see the value of resource dependency-management provided for in the require()
protocol outlined in the CommonJS Specification.
However, I am befuddled as to the benefit of the AMD define()
function's use and purpose.
The CommonJS signature for define is:
define(id?, dependencies?, factory);
Additionally…
- I see people wrapping their Module
Pattern plug-ins with
define()
when BOTH create an object at the global-scope. - A file containing a normal Module Pattern plug-in can be loaded asynchronously as well.
At first, it "seemed" like yet-another plug-in wrapper...until I began to see folks use it alongside the Module Pattern.
So My Questions Are:
- What does the
define()
protocol outlined in CommonJS specification buy me? - Is it somehow more eloquent?
- Is it meant to replace the Modular Pattern?
- Is it somehow faster?
- If so, why?
// main.js
require("foo.js", function(foo) {
console.log(foo === 42); // true
});
//foo.js
/*
define(42);
define({
"foo": "bar"
});
define(["bar.js"], function(bar) {
return bar.foo;
});
*/
define(function() {
return 42;
});
Define is a great way to pass modular objects back without relying on global scope.
The particular API of define varies from library to library though.
Here the basic idea is that you call define in a file to define what that module is. Then when you require the file you get the module. This cuts out the middle man that is global scope.
It's no faster though (It's slower then injecting into global scope).
Using require
and define
you only have two global values.
The particular define
example above matches the requireJS API
这篇关于在CommonJS规范中概述的define()协议是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!