constructor()方法

在做微信小程序的时候,需要对传输的数据进行加密,大牛给我介绍constructor()方法,不是很懂这个但是用了一次,今天来用自己的想法来理解这个方法

——————————————————————————————————————————————————————————————————————————————

基础类BaseReqeust
构造函数中有固定的几个参数 class BaseReqeust{ constructor(){
this.platformId ='aaa'; this.noiseStr=undefined; this.sign=undefined; } } module.exports=BaseReqeust;
const BaseReqeust = require('./BaseRequest')    // 引入JS

class SignValidateRequest extends BaseReqeust {
    constructor() {            // 不处理构造函数
        super();
    }

    // 获得随机字符串
    genNoiseStr(len) {
        len = len || 32;
        let $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        let maxPos = $chars.length;
        let noiseStr = '';
        for (let i = 0; i < len; i++) {
            // Math.random() 产生[0,1)间的数
            // Math.random(x) * y     产生[x,y)之间的数,包括小数
            // Math.floor()        产生一个数值向下取整
            // .charAt()    返回指定位置字符
            noiseStr += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return noiseStr;
    }

    getToSignStr(token){
        let str=[];
        // 获取随机字符串
        if(!this.noiseStr){
            this.noiseStr = this.genNoiseStr(32);
        }

        // 循环给类中的变量进行操作
        this.getValue(str,this);
        str.push(token)
        console.log(str.join(''));

        // 最终返回str,还需要进行MD5加密
        return str.join('');
    }


    getValue(str,obj){
        let thisFields=[];
        for(const field in obj){
            const fieldType = typeof obj[field];
            // 判断值和类型是否一样
            if(fieldType === 'function'){
                continue;
            }
            if(obj[field]===null||obj[field]===undefined){
                continue;
            }
            thisFields.push(field);
        }
        thisFields.sort();

        for(const i in thisFields){
            const field = thisFields[i];
            const fieldType = typeof obj[field];
            // 判断值是否为一个数组
            if(Array.isArray(obj[field])){
                for(const index in obj[field]){
                    this.getValue(str,obj[field][index]);
                }

            }else if(fieldType==='number'||fieldType==='string'||fieldType==='boolean'){
                str.push(obj[field]);
            }else{
                this.getValue(str,obj[field]);
            }
        }
    }
}

module.exports = SignValidateRequest;
class UserRequest extends SignValidateRequests {
  constructor(param) {
    super();
    for (var key in param) {
      this[key] = param[key];    //    获取构造函数,修改其中的参数
    }
  }
}

function encryption(param, url){
  const req = new UserRequest(param);    // 通过构造函数获取对象
  req.sign = encrypt.hexMD5(req.getToSignStr(token));    // 对参数进行赋值
}

———————————————————————————————————————————————————————————————————————————————

待续。。。。。。(吃饭去)

原文地址:https://www.cnblogs.com/ytlds/p/8822490.html