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


寫在文章的最後


既然已經讀到這裏了,拜託大家再用一分鐘時間,將文章轉發到各位的朋友圈,微信羣中。本公衆號的成長需要您的支持!
以上就是今天的文章,歡迎點贊並推薦給您的朋友!

閱讀更多更新文章,請掃描下面二維碼,關注微信公衆號【面向對象思考】