小程序模塊化---邏輯層

1.模塊化的含義?
把一些公共的代碼抽離成爲一個單獨的 js 文件,作爲一個模塊。
模塊只有通過 module.exports 或者 exports 才能對外暴露接口。

exports 是 module.exports 的一個引用,因此在模塊裏邊隨意更改 exports 的指向會造成未知的錯誤。所以更推薦開發者採用 module.exports 來暴露模塊接口。

小程序目前不支持直接引入 node_modules , 開發者需要使用到 node_modules 時候建議拷貝出相關的代碼到小程序的目錄中,或者使用小程序支持的 npm 功能(參考鏈接:https://developers.weixin.qq.com/miniprogram/dev/devtools/npm.html)

部分代碼如下:

//common.js
module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye

function sayHello(name) {
  console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
  console.log(`Goodbye ${name} !`)
}
//index.js
var common = require('../../common/common.js')
 helloMINA: function () {
    common.sayHello('MINA')
  },
  goodbyeMINA: function () {
    common.sayGoodbye('MINA')
  }
  
//index.wxml
<button bindtap="helloMINA"> helloMINA </button>
<button bindtap="goodbyeMINA"> goodbyeMINA </button>

在這裏插入圖片描述2.文件作用域
在 JavaScript 文件中聲明的變量和函數只在該文件中有效;
不同的文件中可以聲明相同名字的變量和函數,不會互相影響。
通過全局函數 getApp 可以獲取全局的應用實例,如果需要全局的數據可以在 App() 中設置。

// app.js
App({
  globalData: 1
})
// a.js
// The localValue can only be used in file a.js.
var localValue = 'a'
// Get the app instance.
var app = getApp()
// Get the global data and change it.
app.globalData++
// b.js
// You can redefine localValue in file b.js, without interference with the localValue in a.js.
var localValue = 'b'
// If a.js it run before b.js, now the globalData shoule be 2.
console.log(getApp().globalData)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章