99热精这里只有精品-黑人一级综合一区二区-在线播放大黑屌大干人妻-樱花草四区区三区四区-久久久一区二区三区成人美女-国产妇女自拍区在线观看-久久精品日韩免费美女视频-亚洲国产午夜美女福利天天看-欧美激情一区二区三区四区五区

0411-39943997
工作時(shí)間:周一至周日 8:30-17:30
技術(shù)文庫(kù)
Technical Library

小程序模塊化的使用方法

標(biāo)簽: 小程序開(kāi)發(fā)   訪(fǎng)問(wèn): 24832018-01-26

文件作用域

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

通過(guò)全局函數(shù) getApp() 可以獲取全局的應(yīng)用實(shí)例,如果需要全局的數(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)

模塊化

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

需要注意的是:

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

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

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

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

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

Tips

  1. tip: require 暫時(shí)不支持絕對(duì)路徑


Copyright? 2020 仟億科技,All rights reserved.