您现在的位置: 万盛学电脑网 >> 程序编程 >> 脚本专题 >> javascript >> 正文

javascript中Require调用js的实例

作者:佚名    责任编辑:admin    更新时间:2022-06-22

 无组织的函数们

在我最初开始写 JavaScript 函数时,通常是这样的:

 代码如下

function fun1() {
  // some code here
}
function fun2() {
  // some other code here
}
...

函数全写在全局环境中,项目很小时,通常不会有什么冲突问题。

但代码多了后,渐渐就发现,函数名称(英文词汇)有点不够用了。于是引入命名空间的概念,开始模块化代码。
命名空间下的函数

在命名空间下,我的代码这样写:

 代码如下

var com = com || {};
com.zfanw = com.zfanw || {};
com.zfanw.module1 = (function() {
  // some code here
  return {
    func1: func1,
    ...
  };
}());
com.zfanw.module2 = (function() {
  // some other code here
  return {
    func1: func1,
    ...
  };
}());
...

本着要面向对象的原则,执行函数通常我要这么写的:

com.zfanw.module1.func1.apply({},['arg1',arg2]);
...

当然,为了少打些字符,我还会在闭包中导入1公共 API 接口:www.45it.com

 代码如下

(function($, mod1) {
  // some code here
  mod1.func1.apply({},['arg1',arg2]);
}(jQuery, com.zfanw.module1));
...

至此,代码冲突的可能性已经很小,但代码依赖的问题,多脚本文件管理、阻塞的问题,渐渐浮出水面 – 命名空间的办法开始捉急。

于是 Require.js2 出场。
Require.js

首先了解下 require.js 里模块的概念3:

    A module is different from a traditional script file in that it defines a well-scoped object that avoids polluting the global namespace. It can ex