小程序模塊化的使用方法

2022-07-30    分類: 網(wǎng)站建設(shè)

文件作用域

在 JavaScript 文件中聲明的變量和函數(shù)只在該文件中有效;不同的文件中可以聲明相同名字的變量和函數(shù),不會互相影響。

通過全局函數(shù) getApp() 可以獲取全局的應(yīng)用實例,如果需要全局的數(shù)據(jù)可以在 App() 中設(shè)置,如:

// app.jsApp({  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)模塊化

可以將一些公共的代碼抽離成為一個單獨的 js 文件,作為一個模塊。模塊只有通過 module.exports 或者 exports 才能對外暴露接口。

需要注意的是:

exports 是 module.exports 的一個引用,因此在模塊里邊隨意更改 exports 的指向會造成未知的錯誤。所以更推薦開發(fā)者采用 module.exports 來暴露模塊接口,除非你已經(jīng)清晰知道這兩者的關(guān)系。

小程序目前不支持直接引入 node_modules , 開發(fā)者需要使用到 node_modules 時候建議拷貝出相關(guān)的代碼到小程序的目錄中。

// common.jsfunction sayHello(name) {  console.log(`Hello ${name} !`)}function sayGoodbye(name) {  console.log(`Goodbye ${name} !`)}module.exports.sayHello = sayHelloexports.sayGoodbye = sayGoodbye

在需要使用這些模塊的文件中,使用 require(path) 將公共代碼引入

var common = require('common.js')Page({  helloMINA: function() {    common.sayHello('MINA')  },  goodbyeMINA: function() {    common.sayGoodbye('MINA')  }})Tips

本文名稱:小程序模塊化的使用方法
分享鏈接:http://www.bm7419.com/news45/183595.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計、營銷型網(wǎng)站建設(shè)網(wǎng)站設(shè)計公司、靜態(tài)網(wǎng)站軟件開發(fā)、用戶體驗

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)