温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

微信小程序实战中如何使用类优化程序结构

发布时间:2022-01-04 18:50:28 来源:亿速云 阅读:122 作者:柒染 栏目:大数据

本篇文章为大家展示了微信小程序实战中如何使用类优化程序结构,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

虽然Javascript是一种脚本语言,但是依然可以定义和使用类。在这个小程序中,将监控点相关的功能做成了一个类。

alarm.js

//alarm.js:

const util = require('./util.js')

const CHECK_BUFFER_SIZE = 3

//构造函数

function Alarm(data){

 this.latitude = data.latitude

 this.longitude = data.longitude

 this.state = data.state

 this.checkBuffer = []

 this.title = data.title

 this.monitor_type = data.monitor_type

 this.action_type = data.action_type

 this.meaia_url = data.media_url

 this.timer = data.timer

}

//定义原型

Alarm.prototype ={

 constructor:Alarm,

 setTitle: function (t) {

   this.title = t

 },

 setMonitorType:function(m_type){

   this.monitor_type = m_type

 },

 setActionType: function (a_type) {

   this.action_type = a_type

 },

 setMedia: function (url) {

   this.media_url = url

 },

 setTimer: function(t_name) {

   this.timer = t_name

 },

 checkLocation: function (latitude, longitude, accuracy) {

   const app = getApp()

   var that = this;

   var distance = util.getDistance(this.latitude, this.longitude, latitude, longitude)

   app.addLog(distance + "," + accuracy)

   if (distance < accuracy) {

     this.checkBuffer.push(1)

   } else {

     this.checkBuffer.push(-1)

   }

   if (this.checkBuffer.length > CHECK_BUFFER_SIZE) {

     this.checkBuffer.shift()

   }

   var sum = 0;

   that.checkBuffer.forEach(function (value) {sum += value})

   if (this.moitor_type == '接近监控点') {

     if (this.state == 'new') {

       if (sum == -CHECK_BUFFER_SIZE) {

         this.state = 'armed'

       }

     } else if (this.state == 'armed') {

       if (sum == CHECK_BUFFER_SIZE) {

         this.state = 'fired'

       }

     }

   } else {

     if (this.state == 'new') {

       if (sum == CHECK_BUFFER_SIZE) {

         this.state = 'armed'

       }

     } else if (this.state == 'armed') {

       if (sum == -CHECK_BUFFER_SIZE) {

         this.state = 'fired'

       }

     }

   }

 },

 excueteAction: function () {

   play.playVoice(this.media_url)

 },

};

module.exports = {

 Alarm:Alarm,

}

代码说明

在alarm.js中,定义了一个名为Alarm的类。

首先定义了一个Alarm构造函数,它以一个对象data作为参数,函数的功能就是从data中取出数据并设定到相应的数据成员上。

接下来定义了一个prototype对象,它的内部又定义了若干函数。所有通过new Alarm获得的对象都以protype中定义的内容作为原型。换言之就是都可以使用prototype中定义的函数。

最后的module.export语句定义的本模块对外公开的功能。

函数的内容我们在后续文章中说明。

类的使用

导入类

首先需要在利用者模块中导入Alarm类。与Alarm.js中的module.export相对应,可以使用以下的方式:

import { Alarm } from './utils/alarm.js'

创建对象,使用对象

var alarm = new Alarm({latitude:38,longitude:120})

alarm.setActionType("播放提示音")

代码下载链接

alarm.js

https://raw.githubusercontent.com/xueweiguo/alarmmap/master/utils/alarm.js

上述内容就是微信小程序实战中如何使用类优化程序结构,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI