W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎勵
可以將一些公共的代碼抽離成為一個單獨(dú)的 js 文件,作為一個模塊。模塊只有通過 module.exports 或者 exports 才能對外暴露接口。
注意:
// common.js
function sayHello(name) {
console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
console.log(`Goodbye ${name} !`)
}
module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye
?在需要使用這些模塊的文件中,使用 require 將公共代碼引入
var common = require('common.js')
Page({
helloMINA: function() {
common.sayHello('MINA')
},
goodbyeMINA: function() {
common.sayGoodbye('MINA')
}
})
在 JavaScript 文件中聲明的變量和函數(shù)只在該文件中有效;不同的文件中可以聲明相同名字的變量和函數(shù),不會互相影響。
通過全局函數(shù) getApp 可以獲取全局的應(yīng)用實(shí)例,如果需要全局的數(shù)據(jù)可以在 App() 中設(shè)置,如:
// 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)
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: