var v = new l();
function l(l, n, t) {
this.http = l,
this.masageService = n,
this.router = t,
this.privaKey = this.getAesKey(16),
this.crypto = {
Encrypt: function(l) {
var n = p.enc.Utf8.parse("t171420100302rsa")
, t = p.enc.Utf8.parse("t171420100302rsa")
, e = p.enc.Utf8.parse(l)
, a = p.AES.encrypt(e, n, {
iv: t,
mode: p.mode.CBC,
padding: p.pad.Pkcs7
});
return p.enc.Base64.stringify(a.ciphertext)
}
};
var e = JSON.parse(this.getUserInfo());
this.head = {
customerId: e.head.customerId,
userCode: e.head.userCode
}
}
v['prototype']['getAesKey'] = function(l) {
l = l || 32;
for (var n = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678", t = n.length, e = "", a = 0; a < l; a++)
e += n.charAt(Math.floor(Math.random() * t));
return e
}
上述代码为啥执行后,报错this.getAesKey is not a function,不是很懂JS,该怎么改。
顺序错了,
1、第二行放到最后
2、28行 v 改成 l
【以下回答由 GPT 生成】
问题的原因是this.getAesKey(16)
在l()
函数中被执行,此时getAesKey
方法还没有被定义。解决这个问题需要先将getAesKey
方法定义在l()
函数的原型上,然后再调用getAesKey
方法。
以下是修改后的代码:
var v = new l();
function l(l, n, t) {
this.http = l;
this.masageService = n;
this.router = t;
this.privaKey = this.getAesKey(16);
this.crypto = {
Encrypt: function(l) {
var n = p.enc.Utf8.parse("t171420100302rsa");
var t = p.enc.Utf8.parse("t171420100302rsa");
var e = p.enc.Utf8.parse(l);
var a = p.AES.encrypt(e, n, {
iv: t,
mode: p.mode.CBC,
padding: p.pad.Pkcs7
});
return p.enc.Base64.stringify(a.ciphertext);
}
};
var e = JSON.parse(this.getUserInfo());
this.head = {
customerId: e.head.customerId,
userCode: e.head.userCode
};
}
// 将getAesKey方法定义在l()函数的原型上
l.prototype.getAesKey = function(l) {
l = l || 32;
var n = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
var t = n.length;
var e = "";
for (var a = 0; a < l; a++) {
e += n.charAt(Math.floor(Math.random() * t));
}
return e;
};
通过将getAesKey
方法定义在l()
函数的原型上,使得在实例化l
对象时可以正常调用getAesKey
方法。这样就解决了报错"this.getAesKey is not a function"的问题。