• 小程序作用域与模块化


    文件作用域

    // 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)
    

    模块化

    可以将一些公共的代码抽离成为一个单独的 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(path) 将公共代码引入

    var common = require('common.js')
    Page({
      helloMINA: function() {
        common.sayHello('MINA')
      },
      goodbyeMINA: function() {
        common.sayGoodbye('MINA')
      }
    })
    

    tip: require 暂时不支持绝对路径

  • 相关阅读:
    Linux基础ls命令
    Linux基础tree命令
    Java银行调度系统
    Java交通灯系统
    Java反射
    Java基础IO流
    Java多线程
    Java集合框架
    Springmvc的一些属性功能
    JS
  • 原文地址:https://www.cnblogs.com/jiqing9006/p/9053389.html
Copyright © 2020-2023  润新知