define 用来定义模块

require 用来加载模块


1

因为定义一个模块,可能会依赖其他模块,当然最简单的情况下是不依赖其他模块,这时就可以这样写:

  1. //Inside file my/shirt.js:
  2. define({
  3. color: "black",
  4. size: "unisize"
  5. });


官方解释:If the module does not have any dependencies, and it is just a collection of name/value pairs, then just pass an object literal to define():


2

定义一个模块,也可能需要先做一些setup工作,假设它也不依赖其他模块,这时可以这样写:

  1. //my/shirt.js now does setup work
  2. //before returning its module definition.
  3. define(function () {
  4. //Do setup work here

  5. return {
  6. color: "black",
  7. size: "unisize"
  8. }
  9. });


官方解释:If the module does not have dependencies, but needs to use a function to do some setup work, then define itself, pass a function to define():



3

定义一个模块,可能会很复杂,既依赖其它一些个模块,又需要一些setup工作,那么这个时候可以这样写:

  1. //my/shirt.js now has some dependencies, a cart and inventory
  2. //module in the same directory as shirt.js
  3. define(["./cart", "./inventory"], function(cart, inventory) {
  4. //return an object to define the "my/shirt" module.
  5. return {
  6. color: "blue",
  7. size: "large",
  8. addToCart: function() {
  9. inventory.decrement(this);
  10. cart.add(this);
  11. }
  12. }
  13. }
  14. );


被依赖的模块会作为参数一次传入到那个function中。

看官方解释:If the module has dependencies, the first argument should be an array of dependency names, and the second argument should be a definition function. The function will be called to define the module once all dependencies have loaded. The function should return an object that defines the module. The dependencies will be passed to the definition function as function arguments, listed in the same order as the order in the dependency array



  1. //Explicitly defines the "foo/title" module:
  2. define("foo/title",
  3. ["my/cart", "my/inventory"],
  4. function(cart, inventory) {
  5. //Define foo/title object in here.
  6. }
  7. );


相信你一看便理解了,不过它里面的学问可以在没事的时候去看看官方的文档说明,也许很有意思的哦。


还有好多其他情况,但记住本质,define是用来定义模块的,require是用来加载模块的,整个库的开发考虑的情况比较多,比如:为了兼容以前的代码,为了适应某些库的使用,某些转换工具的使用,元编程的应用,等等。只要我们抓住本质,理解意思,具体的格式参考官网