微信小程序Component组件调用回调函数this指向不是本页面


在微信小程序中如果在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())
    },

  },
});

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM