您好,登錄后才能下訂單哦!
這篇文章主要講解了在微信小程序中應用ES6 CLASS的實例分析,內容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
ES6 CLASS基本用法
class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return '(' + this.x + ', ' + this.y + ')'; } }
1.1 constructor方法
constructor方法是類的默認方法,通過new命令生成對象實例時,自動調用該方法。一個類必須有constructor方法,如果沒有顯式定義,一個空的constructor方法會被默認添加。
class Point { } // 等同于 class Point { constructor() {} }
上面代碼中,定義了一個空的類Point,JavaScript 引擎會自動為它添加一個空的constructor方法。
1.2 類的實例
生成類的實例的寫法,與 ES5 完全一樣,也是使用new命令。前面說過,如果忘記加上new,像函數(shù)那樣調用Class,將會報錯。
class Point { // ... } // 報錯 var point = Point(2, 3); // 正確 var point = new Point(2, 3);
1.3 取值函數(shù)(getter)和存值函數(shù)(setter)
與 ES5 一樣,在“類”的內部可以使用get和set關鍵字,對某個屬性設置存值函數(shù)和取值函數(shù),攔截該屬性的存取行為。
class MyClass { constructor() { // ... } get prop() { return 'getter'; } set prop(value) { console.log('setter: '+value); } } let inst = new MyClass(); inst.prop = 123; // setter: 123 inst.prop // 'getter'
1.4 this 的指向
類的方法內部如果含有this,它默認指向類的實例。但是,必須非常小心,一旦單獨使用該方法,很可能報錯。
class Logger { printName(name \= 'there') { this.print(\`Hello ${name}\`); } print(text) { console.log(text); } } const logger \= new Logger(); const { printName } \= logger; printName(); // TypeError: Cannot read property 'print' of undefined
上面代碼中,printName方法中的this,默認指向Logger類的實例。但是,如果將這個方法提取出來單獨使用,this會指向該方法運行時所在的環(huán)境(由于 class 內部是嚴格模式,所以 this 實際指向的是undefined),從而導致找不到print方法而報錯。
ES6 CLASS在微信小程序中的應用實例
//index.js import {Card} from './Card/Card.js'; //引用 const app = getApp() Page({ //初始化數(shù)據(jù) data: { cards:{}, }, onLoad: function () { var url = "https://app.******.com/submit_ajax.ashx?action=APP_GetCardslist"; var param = {uid:'37906'}; var carcard = new Card(url,param); var that = this; //假如回調是同步的,可以使用下面的方法直接取值 // var cardData = carcard.getCardData(); carcard.getCardData((data)=>{ //對數(shù)據(jù)源進行判斷 if (data.status == '1') { that.setData({ cards: data.result }) console.log(that.data.cards); } else { wx.showToast({ title: data.msg, icon:'none' }) } }) }, })
var util = require("../../../utils/util.js"); //創(chuàng)建Card對象 class Card { //構造函數(shù),此處提供了兩個參數(shù) constructor(url,parameter) { this.url = url; this.parameter = parameter; } getCardData(cb) { this.cb = cb; util.http(this.url,this.parameter,"POST",this.processCarCardData.bind(this)); } processCarCardData(data) { if (!data) { return; } this.cb(data); } } //class對象是個模塊,使用export把對象輸出出去 export {Card}
//util.js function http(url,parameter,method, callback) { wx.request({ url: url, method: method, data:{parameter}, header: { "Content-type": "application/json" }, success: function (res) { callback(res.data); }, fail: function () { console.log("error"); } }); } module.exports \= { http:http }
看完上述內容,是不是對在微信小程序中應用ES6 CLASS的實例分析有進一步的了解,如果還想學習更多內容,歡迎關注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。