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

Retrieve information about a parent's data related to child events in Vue.js

I'm working with two components nested inside each other. The parent component has a click event that needs to modify the data value of the child component. <template> <div> ..... ..... <my-component :op ...

Challenges with Hangman in JavaScript

As a beginner in JavaScript, I recently developed a simple hangman-like game. However, I encountered some challenges that I need help with. One issue is related to my lettersGuessed array. Currently, the array displays every time a key is pressed and repea ...

Algorithm for searching and calculating with multiple words (Angular/Javascript)

As I work on loading a JSON file from the database containing two fields - words and grade, I face a challenge. Each word in the file is assigned a grade, for example, "true" has a grade of 1 while "lie" has a grade of -1. My goal is to take input from a t ...

Alter the div's HTML content once the Ajax operation is completed

I have a div element that looks like this: <div class="progress" id="progress-bar"></div> I am using the following JavaScript code along with an ajax call to retrieve some data. The data returned is 0, however, the content is not being added ...

Having trouble with the Jquery click event not functioning on an interactive image map in Chrome browser

I currently have an interactive image-map embedded on my website. Here is the HTML code: <div id="italy-map" class="affiancato verticalmenteAllineato"> <div id="region-map"> <img src="./Immagini/transparent.gif" title="Click on ...

Display or conceal elements in Angular based on multiple conditions

Looking to develop a functionality where an array of objects can be shown or hidden based on specific filters. The desired output should be as follows: HTML CODE: Filter: <div (click)="filter(1)"> F1 </div> <di ...

What steps can be taken to troubleshoot an AJAX error that does not display any error messages?

Within my ajax code, I have the following: $(document).ready(function(){ $("form input#dodaj").click(function(){ var s = $("form input#zad").val(); var str = "<li>"+s+"</li>"; $.ajax( { type: "GET", ...

What could be the reason for the electron defaultPath failing to open the specified directory?

Hi, I'm experiencing difficulties opening the directory path (/home/userxyz/Releases/alpha) using electron. This is what I have attempted: I have a similar path on Ubuntu: /home/userxyz/Releases/alpha When trying to access this path with the fo ...

Tips for decreasing the width of a Grid component in React using MUI

Is there a way to adjust the width of the initial Grid element within Material UI, allowing the remaining 3 elements to evenly occupy the extra space? see visual example Would modifying the grid item's 'xl', 'lg', 'md', ...

What are the best practices for implementing media queries in Next.js 13.4?

My media queries are not working in my next.js project. Here is what I have tried so far: I added my queries in "styles.module.css" and "global.css" and imported them in layout.js I included the viewport meta tag under a Head tag in layout.js This is how ...

Exploring the capabilities of require() in nodeJS

I'm wondering about the inner workings of the require() function in a nodeJS application. What exactly does require() return? Let's say I want to utilize two third-party packages: lodash and request. After installing these packages, my code mig ...

How can I access a store getter in Vue after a dispatch action has finished?

I am currently utilizing Laravel 5.7 in combination with Vue2 and Vuex. While working on my project, I have encountered an issue where Vue is not returning a store value after the dispatch call completes. The workflow of my application is as follows: Wh ...

Performing a MongoDB aggregate operation to swap out a set of IDs with their corresponding objects from an array located within the same document

In my collection, I have a variety of documents that look like this: [{ id: 1, name: 'My document 1', allItems: [{ id: 'item1', name: 'My item 1' }, { id: 'item2', name ...

What could be causing the misalignment between the desired output and the response from the AJAX request

Below is a basic JavaScript file I am working with: $.ajax({ url: "is_complete.php", type: "post", success: function (data) { if(data == 1) { } alert("ok") } }) The message "ok" will only be di ...

Jose authentication is encountering issues with verifying JWT

My Next.js/Clerk.js middleware setup looks like this: import { authMiddleware } from "@clerk/nextjs"; import { jwtVerify } from "jose"; export default authMiddleware({ publicRoutes: ["/", "/contact", "/pricin ...

Ways to incorporate External JS and CSS files into Angular 5 (loading files with a delay)

I have encountered some challenges while attempting to import external JS and CSS files into my Angular 5 application. Below is the code snippet that I have tried so far: Component.ts : ngOnInit() { this.loadScript(); // also attempted with ...

"Unleashing the Glamour: Tips for Decorating an Amazing Ajax Pop

I need help styling a magnific pop-up that displays content from a uri. The content is just plain text and I want to avoid using any html code as the popup will be triggered by a button. The current code I have written functions correctly, but the appeara ...

Click to be redirected to the same page on a different store

I have been working on a Shopify project where I implemented a pop-up that appears when the page loads, prompting users to choose between the US and UK websites. Once a user clicks on one of the options, the pop-up either closes (UK) or redirects them to ...

In TypeScript, the choice between using `private readonly` within a class and

I have been contemplating the best method and potential impacts of referencing constants from outside a class within the same file. The issue arose when I was creating a basic class that would throw an error if an invalid parameter was passed: export cla ...

Guide to utilizing exact matching functionality in ExpressJs router

In my ExpressJs application, I have defined two routes like so: router.get("/task/", Controller.retrieveAll); router.get("/task/seed/", Controller.seed); When I make a request to /task/seed/, the Controller.retrieveAll function is call ...