在微信小程序中如果在Component中寫回調函數, 那么this的指向是undefined
Component({ /** * 組件的屬性列表 */ properties: { }, /** * 組件的初始數據 */ data: { }, /** * 組件的方法列表 */ methods: { getData(callback) { if (callback) { callback(); } }, funcA () { console.log(this) //這里的this不是指向Component實例 }, }, lifetimes: { attached: function() { this.getData(this.funcA) }, }, });
解決辦法: 在調用回調函數的時候使用箭頭函數
Component({ /** * 組件的屬性列表 */ properties: { }, /** * 組件的初始數據 */ data: { }, /** * 組件的方法列表 */ methods: { getData(callback) { if (callback) { callback(); } }, funcA () { console.log(this) //這里的this不是指向Component實例 }, }, lifetimes: { attached: function() { this.getData(()=> this.funcA()) }, }, });
