EA&UML日拱一卒-微信小程序实战:位置闹铃 (13)-使用类优化程序结构

虽然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


写在文章的最后


既然已经读到这里了,拜托大家再用一分钟时间,将文章转发到各位的朋友圈,微信群中。本公众号的成长需要您的支持!
以上就是今天的文章,欢迎点赞并推荐给您的朋友!

阅读更多更新文章,请扫描下面二维码,关注微信公众号【面向对象思考】