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

Posted btxlc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信小程序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())
    ,

  ,
);

 

以上是关于微信小程序Component组件调用回调函数this指向不是本页面的主要内容,如果未能解决你的问题,请参考以下文章