Rumah  >  Artikel  >  applet WeChat  >  微信小程序中文件作用域解析

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

一个新手
一个新手asal
2017-09-14 10:32:032424semak imbas


文件作用域

在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 暂时不支持绝对路径

Atas ialah kandungan terperinci 微信小程序中文件作用域解析. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn