微信小程序 教程之模块化

黄舟
Libérer: 2018-05-17 15:06:30
original
2040 Les gens l'ont consulté

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

// app.js  
App({  
 globalData: 1  
})
Copier après la connexion
// 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++
Copier après la connexion
// 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)
Copier après la connexion

模块化
我们可以将一些公共的代码抽离成为一个单独的js文件,作为一个模块。模块只有通过module.exports才能对外暴露接口。

// common.js  
function sayHello(name) {  
 console.log('Hello ' + name + '!')  
}  
module.exports = {  
 sayHello: sayHello  
}
Copier après la connexion

在需要使用这些模块的文件中,使用require(path)将公共代码引入。

var common = require('common.js')  
Page({  
 helloMINA: function() {  
 common.sayHello('MINA')  
 }  
})
Copier après la connexion

以上就是微信小程序 教程之模块化的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!