新聞中心
這篇文章主要介紹微信小程序中文件作用域的示例分析,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

文件作用域
在javaScript文件中聲明的變量和函數(shù)只在該文件中有效;不同的文件中可以生命相同的名字的變量和函數(shù),不會(huì)相互影響。
通過全局函數(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è)模塊化。模塊化只有通過module.exports 或者 exports 才能對(duì)外暴露接口。
需要注意的是:
wxports是module.exports的一個(gè)引用,因此在模塊化里邊隨意更改exports的指向會(huì)造成未知的錯(cuò)誤。所以更推薦開發(fā)者采用module.exports來暴露模塊接口,除非你已經(jīng)清晰知道這兩者的關(guān)系。小程序目前不支持直接引入
node_modules,開發(fā)者需要使用到node_modules時(shí)候建議拷貝出相關(guān)的代碼到小程序的目錄中
//commont.jsfunction sayHello(name){
console.log('------ hello ' + name +'=====');
}
module.exports.sayHello = sayHello;//index.jsvar common = require('../commont/commont.js');
Page({ //加載視圖的時(shí)候
onLoad:function (){
//調(diào)用
common.sayHello('dqk');
})控制臺(tái)輸出:

提示
require 暫時(shí)不支持絕對(duì)路徑
以上是“微信小程序中文件作用域的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
分享題目:微信小程序中文件作用域的示例分析-創(chuàng)新互聯(lián)
本文網(wǎng)址:http://www.dlmjj.cn/article/spphh.html


咨詢
建站咨詢
