收藏
回答

小程序中自定义js文件的this指向问题

// let conf = require('../conf/conf.js');
let conf = require('../config/config');
let principal = conf.CLIENT_TOKEN;
let loading = false
let http = {
  globalData: {
    SERVER_ERROR: '连接出现异常',
    SEVER_EXCEPTION: '服务器异常',
    INTERNET_ERROR: '网络似乎不太顺畅',
    NOID: '登陆失败,请重新登录',
    staticAccess: conf.MSA_ROOT + '/file/get?guid=', //拍摄照片路径
  },
  request: async function (setting) {
    if (!loading) {
      wx.showLoading({
        title: '加载中',
      })
      loading = true
    }
    let that = this;
    // console.log(http)
    console.log(this)
    console.log(that)
    //封装请求
    var defaultSetting = {};
    return new Promise((resolve, reject) => {
      console.log('this',this)
      if (!setting.success) {
        setting.success = function (res) {
          resolve(res.data)
          if (loading) {
            wx.hideLoading()
            loading = false
          }
          if (!res.data.success) {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }
      }
      defaultSetting = that.updateSetting(setting, defaultSetting);
      defaultSetting.header = that.getHeader(defaultSetting.method);


      const app = getApp();
      // let token = app.context.userInfo.accessToken;
      let token = wx.getStorageSync('userInfo') && wx.getStorageSync('userInfo').accessToken;
      defaultSetting.url = conf.CERT_ROOT + defaultSetting.url.concat(defaultSetting.url.indexOf('?') >= 0 ? '&' : '?').concat(`accessToken=${token}`);


      const storage = app.system.storage;


      Object.assign(defaultSetting.header, setting.header);


      if (setting.success) {
        // if (true) {
        // console.log('success', setting)
        defaultSetting.success = function (res) {
          // console.log('......请求参数配置......');
          // console.log(defaultSetting);
          // console.log('......请求响应结果......');
          that.data = res.data
          let code = res.data.code;
          if (code == 400002 || code == 400001) {
            wx.showModal({
              showCancel: false,
              content: res.entity || '登录过期,请重新登录',
              success: function () {
                storage.rm("userInfo");
                wx.clearStorageSync();
                wx.reLaunch({
                  url: '/pages/login/login'
                })
              }
            });
            return false;
          }


          try {
            setting.success(res);
          } catch (e) {
            throw e;
          }
        }
      }
      wx.request(defaultSetting)
    })
  },
  uploadFile: function (setting) {
    let that = this;
    //封装请求
    var defaultSetting = {};


    defaultSetting = that.updateSetting(setting, defaultSetting);
    if (setting.success) {
      defaultSetting.success = function (res) {
        var statusCode = res.statusCode;


        console.log('......上传响应结果......');
        console.log(res);


        that.statusCodeManage(statusCode);
        try {
          setting.success(res);
        } catch (e) {
          throw e;
        }
      }
    }
    defaultSetting.header = that.getHeader(defaultSetting.method);
    console.log('......上传参数配置......');
    console.log(defaultSetting);


    return wx.uploadFile(defaultSetting);
  },
  statusCodeManage: function (code) {
    //管理http状态码
    switch (code.toString()) {
      case '500':
        wx.showToast({
          title: this.globalData.SERVER_ERROR,
          icon: 'none',
          image: '',
          duration: 2000,
          mask: true
        })
        break;
      case '502':
      case '503':
      case '504':
        this.showModal({
          content: this.globalData.INTERNET_ERROR
        });
        break;
      default:
        break;
    }
  },
  updateSetting: function (setting, defaultSetting) {
    for (var key in setting) {
      defaultSetting[key] = setting[key];
    }
    return defaultSetting;
  },
  showModal: function (options) {
    options.confirmColor = '#294fdf';
    wx.showModal(options);
  },
  getHeader: function (method) {
    let that = this;
    let requestId = that.getRequestId();
    let timestamp = new Date().getTime();
    method = method.toLowerCase();


    if (method === 'get') {
      return {
        'REQUEST_ID': requestId,
        'principal': principal,
        'cache-control': 'no-cache',
        'content-type': 'application/json',
        'timestamp': timestamp
      }
    } else if (method === 'post') {
      return {
        'REQUEST_ID': requestId,
        'principal': principal,
        'content-type': 'application/x-www-form-urlencoded',
        'timestamp': timestamp
      }
    }
    return {};
  },
  getRequestId: function () {
    let id = [];
    for (var i = 0; i < 20; i++) {
      id.push((((new Date().getTime() * Math.random()) * 0x10000) | 0).toString(16));
    }
    return id.join('').slice(1, 65);
  }
}


// module.exports = http.request;
let myRequest = http.request
export {myRequest}

按照js的规则 此时的this指向应该是当前的http变量

而有时候指向的是underfind 有时候确实 WIndow?

回答关注问题邀请回答
收藏

2 个回答

  • 微盟
    微盟
    02-05

    用箭头函数, 或者 async request (setting) {xxx}

    02-05
    有用
    回复 1
    • 追随
      追随
      02-08
      按照正常来说这里使用function也是没问题的 当时使用箭头函数得到的结果是undefined
      02-08
      回复
  • 追随
    追随
    02-04

    当我把anync 去除时 this指向却为underfind

    02-04
    有用
    回复
登录 后发表内容
问题标签