Home > WeChat Applet > Mini Program Development > WeChat Mini Program Tutorial Modularization

WeChat Mini Program Tutorial Modularization

黄舟
Release: 2018-05-17 15:06:30
Original
2101 people have browsed it

File Scope
Variables and functions declared in a JavaScript file are only valid in that file; variables and functions with the same name can be declared in different files without affecting each other.
You can get the global application instance through the global function getApp(). If you need global data, you can set it in App(), such as:

// app.js  
App({  
 globalData: 1  
})
Copy after login
// 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++
Copy after login
// 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)
Copy after login

Modularization
We can put some common code Extract it into a separate js file as a module. Modules can only expose interfaces to the outside world through module.exports.

// common.js  
function sayHello(name) {  
 console.log('Hello ' + name + '!')  
}  
module.exports = {  
 sayHello: sayHello  
}
Copy after login

In the files that need to use these modules, use require(path) to introduce the public code.

var common = require('common.js')  
Page({  
 helloMINA: function() {  
 common.sayHello('MINA')  
 }  
})
Copy after login

The above is the modular content of the WeChat applet tutorial. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template