AMD:javascript上下文的目的是什么? [英] AMD: what is the purpose in javascript context?

查看:57
本文介绍了AMD:javascript上下文的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于AMD(异步模块定义),我读到这样的阶段:

Regarding AMD (Asynchronous Module Definition ) I read the phase like this:

AMD格式来自于想要一种比以下格式更好的模块格式 今天的写了一堆带有隐式依赖关系的脚本标签, 您必须手动订购",并且易于使用 直接在浏览器中.

The AMD format comes from wanting a module format that was better than today's "write a bunch of script tags with implicit dependencies that you have to manually order" and something that was easy to use directly in the browser.

javascript上下文的目的是什么?你能举个例子吗?使用AMD的专业观点?

What is the the purpose in javascript context? Can you make some example? pro et contro of using AMD?

推荐答案

早在JavaScript获得本机模块系统之前,将脚本放到页面上的唯一方法就是<script>元素.这些命令按它们在HTML上出现的顺序依次执行.这意味着,如果您的脚本依赖于jQuery,则jQuery的<script>必须位于脚本的<script>之前.否则,它会炸毁.

Long before JavaScript gained a native module system, the only way to put scripts onto a page were <script> elements. These executed in sequence, in the order they appear on the HTML. This means that if your script relied on jQuery, then jQuery's <script> has to come before your script's <script>. Otherwise, it blows up.

从逻辑上将一个应用拆分为多个文件并不少见,尤其是随着应用的增长.但是使用这种手动订购脚本的系统很快就变成了噩梦.您的脚本具有隐式依赖关系,其管理在其他位置定义.这就是AMD出现的地方.

It's not uncommon to logically split an app into multiple files, especially as the app grows. But using this system of manually ordering scripts becomes a nightmare quickly. Your scripts have implicit dependencies whose management is defined elsewhere. This is where AMD comes in.

AMD是模块规范,而RequireJS是此类系统的实现.简而言之,它是对代码的包装:1)使脚本保持惰性直到被调用; 2)允许脚本显式定义其依赖关系; 3)允许模块系统确定哪些依赖关系以什么顺序执行.

AMD is a module specification and RequireJS is an implementation of such system. Simply put, it's a wrapper around your code that 1) keeps your script inert until invoked, 2) allows your script to explicitly define its dependencies and, 3) allows the module system to work out which dependencies execute in what order.

这是一个粗略的例子:

// your-app.js
define(['jquery', 'underscore'], function($, _){
  // Your script sits in this "wrapper" function.
  // RequireJS now knows app.js needs jquery and underscore.
  // It loads and executes them first before your script.
})

// jquery.js
define('jquery', [], function(){
  // jQuery stuff
  return jQuery
})

// underscore.js
define('underscore', [], function(){
  // underscore stuff
  return underscore
})

// Then on your HTML, load up your app.
<script data-main="path/to/app.js" src="path/to/require.js"></script>

这篇关于AMD:javascript上下文的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆