Utilizing the keyword 'this' within a function of a JavaScript class that is invoked with the .map method

I am working with the RegisterUser class which contains various methods and properties:

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(Buffer.from(this.username, 'utf8'));
  }

  signPreKey(key){
    var publicKey = key.publicKey;
    var signature = this.identity.sign(publicKey);
    
    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 = Buffer.concat([Buffer.from(cipher.update(this.identity.secretKey)), Buffer.from(cipher.final())]);

    return encrypted;
  }
}

However, when I call .data() on a new instance of this class, I encounter an issue:

I receive the error message "Cannot read property 'identity' of undefined" in the signPreKey function.

Is there a way to utilize .map without replacing the context of this? Any suggestions would be greatly appreciated!

Answer №1

To specify the context of the function, consider using bind().

  get encryptedMessages(){
    var encryptFunc = this.encryptMessage.bind(this);
    return this.messages ? this.messages.map(encryptFunc) : null;
  }

Alternatively, you can provide `this` as the second argument to map():

  get encryptedMessages(){
    var encryptFunc = this.encryptMessage;
    return this.messages ? this.messages.map(encryptFunc, this) : null;
  }

Answer №2

A great way to utilize the array map method is by providing a second argument for specific purposes.

According to information from MDN:

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

To achieve this, simply include the desired thisArg as the second argument like this:

return this.preKeys ? this.preKeys.map(signFunc, this) : null;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for selecting multiple potions from a JSON file in a React Native project

I need help with highlighting multiple options from an array in React Native. Currently, when I click on an option, it highlights that option but de-highlights the previous one. How can I modify my code to allow for selecting and highlighting multiple opti ...

What could be causing the mysql-event to not function properly in a Node.js environment?

const MySQLEvents = require('mysql-events'); const databaseInfo = { host: 'localhost', user: 'root', password: '' //blank password }; const mysqlEventWatcher = MySQLEvents(databaseInfo); console.log(mys ...

Submitting modal form information using AJAX to PHP

As a novice in the realm of web programming, I find myself seeking some guidance to untangle a riddle. Regrettably, my grasp of the basics still leaves much to be desired. Within my main page, view.adminsettings.php, I've designated a Navigation DIV ...

Encountering an issue while invoking the helper function in Vuejs

Main view: <script> import { testMethod1 } from "../helper"; export default { methods: { init(){ console.log("Res:", testMethod1()); } } } </script> Helper: import DataService from "../services/data. ...

Webpack is having trouble locating images within Nextjs

When I import static images with no issues using npm run dev, everything runs smoothly. However, when attempting to utilize npm run build or next build, it fails and prevents deployment to Vercel. next info Operating System: Platform: win32 ...

Having trouble with the react event handler for the renderedValue component in Material UI?

I am facing an issue while trying to utilize the onDelete event handler within the chip component using Material UI in the code snippet below. Upon clicking on the chip, it triggers the Select behavior which opens a dropdown menu. Is there a way to modif ...

There was an error: "TypeError: Unable to access the equipmentImage property of

Help needed! I am encountering a strange error while trying to upload an equipment image from postman as form data. The error states: Type Error; Cannot read property equipmentImage. I am using express-fileupload for the image upload process. Can someone ...

Ensure that the form is validated even when setState is not executed immediately

I am currently working on a form in React and I am facing an issue with validation. When the Submit Form button is clicked without filling in the input fields, an error should be displayed. This part is functioning correctly. However, even when the fields ...

Ways to reload the page following the submission of a form

I implemented a fade dialog to present a form, and successfully submitted the form using ajax to create a new record in the database. Now, I am facing an issue where I cannot refresh the page after the ajax call finishes. Despite attempting to use JavaScr ...

JQuery is unable to initiate a keyup event

I am currently utilizing jQuery in a web application. On one of my pages, I have set up an event listener for keypresses as shown below: document.addEventListener('keyup', function (event) { event.preventDefault(); var key = event.k ...

Is there a problem with addEventListener returning false?

What does keeping the third parameter as false in the line below signify? var el = document.getElementById("outside"); el.addEventListener("click", modifyText, false); ...

The definitive method for resolving synchronization problems between Protractor and Angular

The Issue at Hand: We recently encountered a common error while attempting to open a specific page in our application during a Protractor end-to-end test: Error: We timed out waiting for asynchronous Angular tasks to complete after 50 seconds. This cou ...

One click activates the countdown timer, while a second click on the same button pauses it

How can I create a button that allows me to start the countdown timer on the first click and pause it on the second click? I want both functionalities in the same button. Here is an image for reference: https://i.stack.imgur.com/fuyEJ.png I currently ha ...

Looking to retrieve the value of a selected checkbox within a horizontally laid out HTML table

Trying to extract values from a table with a horizontal header when checkboxes are selected. The goal is to retrieve the values of the selected column for all rows. Code snippet provided below. <script src="https://ajax.googleapis.com/ajax/libs/jquer ...

Unable to receive data in an array with Vuejs

Here is the code snippet I am working with: let data = res.data.data; console.log('data: ', data) const list = []; for(let i = 0; i < data.length; i++){ console.log('data i: ', data[i]) //this line is not being printed in the ...

Is it possible to create two separate Express sessions simultaneously?

I am encountering an issue with my Passport-using application that has a GraphQL endpoint and a /logout endpoint. Strangely, when I check request.isAuthenticated() inside the GraphQL endpoint, it returns true, but in the /logout endpoint, it returns false. ...

There is an absence of the 'Access-Control-Allow-Origin' header on the requested resource despite its existence

Currently, I am working on developing an application using Django and Phonegap. While attempting to send an Ajax Request with the following function: <script> $.ajax({ url: "http://192.168.0.101/commerce/pro ...

Calculate the time difference between the stroke of midnight on a specific date and the present moment using JavaScript, node.js, and

Looking for a way to determine if the current moment is less than 3 minutes after midnight of the next date using a JavaScript Date object (e.g. 09.08.2020 15.45). This condition should evaluate to true for times ranging from 09.09.2020 00:00 up until 09.0 ...

The addition and deletion of classes can sometimes lead to disruptions in the DOM

I've been struggling to phrase this question for a while now. I'm working on a single-page e-commerce site that operates by modifying the HTML in divs and using CSS along with JQuery to show and hide those divs. My problem arises when, occasional ...

Encountering issues while executing a grunt.js task

Utilizing the uncss task with grunt.js to optimize my CSS file by eliminating unnecessary rules has been a goal of mine. If you're interested, you can find more about uncss here: https://github.com/addyosmani/grunt-uncss This is how my Gruntfile.js ...