我有以下课程:
class RegisterUser {
constructor(username, password, ispublic){
this.username = username;
this.password = password;
this.ispublic = ispublic;
this.identity = crypto.signKey();
this.preKeys = [];
if (ispublic){
this.preKeys = crypto.getPreKeys(10);
}
}
get data(){
return {
identity_key: this.identity.publicKey,
username: this.username,
usernameSignature: this.usernameSignature,
signedPreKeys: this.signedPreKeys,
ispublic: this.ispublic
}
}
get usernameSignature(){
return this.identity.sign(buf(this.username, 'utf8'));
}
signPreKey(key){
var publicKey = key.publicKey;
var signature = this.identity.sign(pub);
return {
publicKey: publicKey,
signature: signature
}
}
get signedPreKeys(){
var signFunc = this.signPreKey;
return this.preKeys ? this.preKeys.map(signFunc) : null;
}
get encryptedIdentity(){
var cipher = ncrypto.createCipher('aes192', this.password);
var encrypted = new Buffer(cipher.update(this.identity.secretKey));
return Buffer.concat([encrypted, new Buffer(cipher.final())]);
}
}
在这个类的新实例化实例上调用.data()
时,我得到:
无法在signPreKey函数中读取未定义的属性'identity'。
有没有办法以不会取代.map
的方式使用this
?
答案 0 :(得分:3)
您可以使用bind()
来强制功能的上下文。
get signedPreKeys(){
var signFunc = this.signPreKey.bind(this);
return this.preKeys ? this.preKeys.map(signFunc) : null;
}
或者,将this
作为第二个参数传递给map()
:
get signedPreKeys(){
var signFunc = this.signPreKey;
return this.preKeys ? this.preKeys.map(signFunc, this) : null;
}
答案 1 :(得分:2)
当然,数组map
方法完全为此目的采用第二个参数。
来自MDN:
var new_array = arr.map(callback[, thisArg])
只需传递你想要的thisArg
作为第二个参数:
return this.preKeys ? this.preKeys.map(signFunc, this) : null;