可以將一些公共的代碼抽離成為一個單獨的 js 文件,作為一個模塊。模塊只有通過 module.exports 或者 exports 才能對外暴露接口。
1. common.js
1 // common.js 2 function sayHello(name) { 3 console.log(`Hello ${name} !`) 4 } 5 function sayGoodbye(name) { 6 console.log(`Goodbye ${name} !`) 7 } 8 9 /** 10 * 對外接口設置。 11 * 可以使用 module.exports 或 exports 12 * 推薦使用 module.exports 設置接口函數 13 **/ 14 module.exports.sayHello = sayHello 15 exports.sayGoodbye = sayGoodbye
2. 在需要的js文件內,采用 require 引入common.js模塊,示例:
1 // 引用common.js模塊 2 // require僅支持相對路徑 3 // 調用方式采用指針方式,比如: common.sayHello 4 var common = require('common.js') 5 6 Page({ 7 helloMINA: function() { 8 common.sayHello('MINA') 9 }, 10 goodbyeMINA: function() { 11 common.sayGoodbye('MINA') 12 } 13 })