小程序如何面向对象编程
发布于 5 年前 作者 wanjuan 2597 次浏览 来自 问答
  • 需求的场景描述(希望解决的问题)
Page({
  onload(){
let app = getApp()
let that = this
 let customer = new customer(app ,that )
}
})
 
function customer(app,indexPage){
   this.app= app
   this.api= '//api地址
   this.appid= ''//appid
   // this.indexPage = indexPage
}
customer.prototype.login=function(){
  let result ={}
  let thatt = this
  let  url = this.api + "地址"
  let form_data = {}
  wx.login({
    success: function (res) {
      let client_code = res.code
          wx.request({
            url: url,
            data: {
              app_id: thatt.appid,
              client_code: client_code,
              scene: '101',
            },
            method: 'POST',
            success: function (res) {
              if (res.data.status == 'success') {
                result=res.data.data
                console.log(result)
               //  thatt.indexPage.setData({ login_info: res.data.data })
              } else { systemAlert(res.data.info); }
            },
            fail: function (res) { systemAlert(res.errMsg); }
          })
    
    },
    fail: function (res) { systemAlert('登陆失败'); }
  })
}

为什么这个时候我登陆成功以后为什么不能用thi.setData({})

10 回复

官方并没有这个方法,只是再面向对象的写法里,如果要调用this.setData需要解决thi的指向问题就行了,

最好搞清楚this的作用域以及function.bind这两个东西

不是,就是把对象中的对象中的this作为行参,将page中的this作为实参,仅此而已,但因为login的回调,作用域发生变化,可以用es6箭头,但如果不用传参的this指向的也只是customer而不是page,这个就是有点绕。

代码并没有问题

 this.indexPage.setData请问楼主,官方有介绍这个方法吗,如果有可以截图看看吗?

已经解决了,需要使用thatt.indexPage.setData({ login_info: res.data.data })

你好,请具体描述问题出现的流程,并提供能复现问题的简单代码片段(https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html)。

简单说 你用es6的箭头函数吧 this的作用域默认指到外面

其实只要对象中的this.setData中的this指向page中的this即可,

直接thatt.setData({})

如果跨页面可以存成app.globalData.({})

回到顶部