1

I have the following class:

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())]);
  }
}

When .data() is called on a newly instantiated instance of this class, I get:

Cannot read property 'identity' of undefined" in the signPreKey function.

Is there a way to use .map in a way that will not replace this?

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
Sneaky Beaver
  • 705
  • 2
  • 8
  • 15

2 Answers2

3

You can use bind(), which forces the context of the function.

  get signedPreKeys(){
    var signFunc = this.signPreKey.bind(this);
    return this.preKeys ? this.preKeys.map(signFunc) : null;
  }

Alternately, pass this as the second argument to map():

  get signedPreKeys(){
    var signFunc = this.signPreKey;
    return this.preKeys ? this.preKeys.map(signFunc, this) : null;
  }
Scimonster
  • 32,893
  • 9
  • 77
  • 89
2

Sure, the array map method takes a second argument exactly for this purpose.

From MDN:

var new_array = arr.map(callback[, thisArg])

Just pass the thisArg you want as the second argument like so:

return this.preKeys ? this.preKeys.map(signFunc, this) : null;
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171