微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

微信小程序中文件作用域解析


文件作用域

在javaScript文件中声明的变量和函数只在该文件中有效;不同的文件中可以生命相同的名字的变量和函数,不会相互影响。
通过全局函数getApp() 可以获取全局的应用实列,如果需要全局的数据可以在app() 中设置,如:

//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 才能对外暴露接口。
需要注意的是:

  • wxportsmodule.exports一个引用,因此在模块化里边随意更改exports 的指向会造成未知的错误。所以更推荐开发者采用module.exports 来暴露模块接口,除非你已经清晰知道这两者的关系。

  • 小程序目前不支持直接引入node_modules,开发者需要使用到node_modules 时候建议拷贝出相关的代码小程序的目录中

//commont.jsfunction sayHello(name){
    console.log('------  hello    ' + name +'=====');
}
module.exports.sayHello = sayHello;
//index.jsvar common = require('../commont/commont.js');
Page({    //加载视图的时候
  onLoad:function (){
   //调用
    common.sayHello('dqk');
})

控制台输出:

这里写图片描述

提示

require 暂时不支持绝对路径

原文地址:https://www.jb51.cc/weapp/1202638.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。