if(xx){ //....... } else{ //xxxxxxxxxxx } for(var i=0; i<10; i++){ //........ } element.onclick = function(){ //....... }
<script type="text/javascript" src="a.js"></script> <script type="text/javascript" src="b.js"></script>
modA = function(){ var a,b; //變量a、b外部不可見 return { add : function(c){ a + b + c; }, format: function(){ //...... } } }()
app.util.modA = xxx; app.tools.modA = xxx; app.tools.modA.format = xxx;
app.tools.modA.format();
(function(window){ //代碼 window.jQuery = window.$ = jQuery;//經過給window添加屬性而暴漏到全局 })(window);
//math.js exports.add = function() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) { sum += args[i++]; } return sum; };
//increment.js var add = require('math').add; exports.increment = function(val) { return add(val, 1); };
//program.js var inc = require('increment').increment; var a = 1; inc(a); // 2
//可使用exprots來對外暴漏API module.declare(function(require, exports, module) { exports.foo = "bar"; });
//也能夠直接return來對外暴漏數據 module.declare(function(require) { return { foo: "bar" }; });
//a.js define(function(){ console.log('a.js執行'); return { hello: function(){ console.log('hello, a.js'); } } });
//b.js define(function(){ console.log('b.js執行'); return { hello: function(){ console.log('hello, b.js'); } } });
//main.js require(['a', 'b'], function(a, b){ console.log('main.js執行'); a.hello(); $('#b').click(function(){ b.hello(); }); })
define(['a', 'b', 'c', 'd', 'e', 'f', 'g'], function(a, b, c, d, e, f, g){ ..... })
define(function(){ console.log('main2.js執行'); require(['a'], function(a){ a.hello(); }); $('#b').click(function(){ require(['b'], function(b){ b.hello(); }); }); });
var a = require('a'); a.hello(); $('#b').click(function(){ var b = require('b'); b.hello(); });
//d.js define(function(require, exports, module){ console.log('d.js執行'); return { helloA: function(){ var a = require('a'); a.hello(); }, run: function(){ $('#b').click(function(){ var b = require('b'); b.hello(); }); } } });
require(['d'], function(d){ });
//a.js define(function(require, exports, module){ console.log('a.js執行'); return { hello: function(){ console.log('hello, a.js'); } } });
//b.js define(function(require, exports, module){ console.log('b.js執行'); return { hello: function(){ console.log('hello, b.js'); } } });
//main.js define(function(require, exports, module){ console.log('main.js執行'); var a = require('a'); a.hello(); $('#b').click(function(){ var b = require('b'); b.hello(); }); });
var b = require.async('b'); b.hello();
//方式一, a.js export var a = 1; export var obj = {name: 'abc', age: 20}; export function run(){....}
//方式二, b.js var a = 1; var obj = {name: 'abc', age: 20}; function run(){....} export {a, obj, run}
import {run as go} from 'a' run()
module foo from 'a' console.log(foo.obj); a.run();