微信小程序开发手册: 逻辑层模块化

2018-02-0402:07:43APP与小程序开发Comments2,674 views字数 1101阅读模式

文件作用域

在JavaScript文件中声明的变量和函数只在该文件中有效;不同的文件中可以声明相同名字的变量和函数,不会互相影响。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/783.html

通过全局函数getApp()可以获取全局的应用实例,如果需要全局的数据可以在App()中设置,如:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/783.html

// 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)

模块化

我们可以将一些公共的代码抽离成为一个单独的js文件,作为一个模块。模块只有通过module.exports或者 exports才能对外暴露接口。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/783.html

需要注意的是:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/783.html

  • exportsmodule.exports的一个引用,因此在模块里边随意更改exports的指向会造成未知的错误。所以我们更推荐开发者采用module.exports来暴露模块接口,除非你已经清晰知道这两者的关系。
  • 小程序目前不支持直接引入node_modules,开发者需要使用到node_modules时候建议拷贝出相关的代码到小程序的目录中。

 文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/783.html

// common.js
function sayHello(name) {
  console.log('Hello ${name} !')
}
function sayGoodbye(name) {
  console.log('Goodbye ${name} !')
}

module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye

​在需要使用这些模块的文件中,使用require(path)将公共代码引入。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/783.html

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

Tips

1. tip:require暂时不支持绝对路径文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/783.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/xcx/783.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定