Accessing a property's value from a different property within a Class' initialization function

I encountered a challenge while trying to access the value returned in one method within a property of another method belonging to a different constructor. The specific error message I received was "TypeError: Cannot read property 'name' of undefined."

class Loans {
  constructor(user, loanAmount, tenor, id = 0, status = 'pending', repaid = 'false') {
    this.id = id + 1;
    this.user = user;
    this.loanAmount = loanAmount;
    this.tenor = tenor;
    this.status = status;
    this.repaid = repaid;
    this.interest = (function interest() {
      return (loanAmount * 0.05);
    }());
    this.monthlyInstall = (function monthlyInstall() {
      return (loanAmount + this.interest) / tenor;
    }());
    this.balance = (function balance() {
      return (loanAmount + interest);
    }());
    this.createdAt = new Date().toLocaleString();
  };

};
const loan = new Loans('steve.jobs', 50000, 5);
console.log(loan);

However, when attempting to execute the code, I encountered the following error message:

      return (loanAmount + this.interest) / tenor;
                                ^

TypeError: Cannot read property 'interest' of undefined
    at monthlyInstall (C:\Users\DEBAYO\Desktop\JavaScript\Challenges\testing.js:183:33)
    at new Loans (C:\Users\DEBAYO\Desktop\JavaScript\Challenges\testing.js:184:6)

Answer №1

For those seeking a dynamic amount that updates based on value changes, incorporating functions is essential. In the code snippet provided below, I have implemented these as defined functions to allow for automatic updates when calculating variables are modified.

class Loans {
  constructor(user, loanAmount, tenor, id = 0, status = 'pending', repaid = 'false') {
    this.id = id + 1;
    this.user = user;
    this.loanAmount = loanAmount;
    this.tenor = tenor;
    this.status = status;
    this.repaid = repaid;
    this.createdAt = new Date().toLocaleString();
  };
  
  interest = () => (this.loanAmount * 0.05);
  monthlyInstall = () => (this.loanAmount + this.interest()) / this.tenor;
  balance = () => (this.loanAmount + this.interest());
};
const loan = new Loans('steve.jobs', 50000, 5);
console.log(loan);
console.log(loan.interest());
console.log(loan.monthlyInstall());
console.log(loan.balance());
loan.tenor = 6;
console.log(loan);
console.log(loan.interest());
console.log(loan.monthlyInstall());
console.log(loan.balance());

Answer №2

instead of

this.monthlyInstall = (function monthlyInstall() {
      return (loanAmount + this.interest) / tenor;
    }());

simply use

 this.monthlyInstall = (loanAmount + this.interest) / tenor;

Alternatively, ensure to include the "this" reference when calling your monthlyInstall() method to specify its context.

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

displaying a div as a pop-up within an ASP.NET MVC 4 web application

One aspect of my asp.net MVC 4 application involves a partial view structured like so: <form class="qty-add" action="#" method="POST"> <label>Qty:</label> <div class="inp-controller"> <a href="#" c ...

Error encountered in Next.JS when calling getInitialProps(ctx) due to undefined ctx variable

This is my code import NavLayout from "../../components/Navigation/Navigation"; export default function WorldOfWarcraft({ game }) { return (<NavLayout> {game.link} </NavLayout>) } WorldOfWarcraft.getInitialProps = as ...

What is the process of converting a file into a binary stream using Javascript?

I'm currently in the process of building a website using Next.js and I want to upload a file to OneDrive using the Microsoft Graph REST API. The documentation states that the request body should be the binary stream of the file you wish to upload, bu ...

Hough transformation in JavaScript with Node.js

Attempting to implement a 1-dimensional version of the Hough transform, focusing on optimizing for reduced dimensions based on minor properties. Included is the code and sample image with input and output visuals. Questioning what could be going wrong in ...

Is the node certificate store limited to reading only from a predefined list of certificates?

Is there a way to add a new certificate to the list of certificates node trusts, even after some struggle? It appears that Node only trusts certificates hardcoded in its list located here: https://github.com/nodejs/node/blob/master/src/node_root_certs.h ...

React component state change in reverse

As I work on a simple login form component, I encountered an issue where clicking on the form should make it disappear and only display my JSON data. However, due to my limited experience with React state management, I seem to be achieving the opposite eff ...

Tips for accurately determining the count, rather than the character length, of JSON data

After running my code, I believe it returns a JSON array. The resulting JSON array is then stored in a JavaScript variable called 'result'. When I console.log(result); in Firefox, the output shown is: [{"id":"G24","value":"Zas, S"},{"id":"G75" ...

Ways to showcase a JSON menu with a single level

I have a json file containing links to all the images in a specific folder, as shown below: ["http://img1.png","http://img2.png","http://img3.png","http://img4.png"] I would like to create a <ul> list using this data, but I'm not sure how to d ...

Perform a series of database queries one after the other, ensuring they are completed before

Although the database queries themselves are working fine, I am facing an issue with executing them sequentially in Node. Here is an example of the queries I need to execute in order: DELETE FROM myTable; INSERT INTO myTable(c1, c2, c3) VALUES (x, y, z); ...

Is there a benefit to using the Angular LocalStorageModule alongside angular-cache?

To configure the angular-cache, follow this setup: app.service('myService', function ($angularCacheFactory) { // This cache will synchronize with localStorage if available. Upon each app load, it will attempt to retrieve any previously save ...

What could be causing the input event not to be triggered consistently when I select or highlight text?

I have implemented a 4-digit pin field with a specific behavior: when a field is filled, the focus automatically shifts to the next field (the cursor moves to the next input field). If text in a field is deleted, the text in that field is also removed and ...

Problem arises when attempting to slice an array that is defined in the parent component

Seems like a simple mistake, but here's what happened: In the main parent component, I have an array defined: ... <object-list-grid v-bind:objects="objectsList" ></object-list-grid> ... data() { return { ... ...

Is there a way to implement a function in Javascript or CSS where hovering over a button will cause a div to scroll either left or right

I am working on creating a unique photo gallery layout with a description block positioned below the images. My goal is to incorporate two arrow buttons, one on each side of the photos, that will trigger a scrolling effect when hovered over - shifting the ...

What is the best way to play a video from a certain time point in a React application?

How can I make my component automatically play from a specific time like 00:07:12,600 instead of starting from the beginning? import style from './Hero.module.css'; import Image from 'next/image'; import ReactPlayer from 'react-pla ...

Tips for transforming a container div into a content slider

Working with Bootstrap 3, a custom div has been created as shown below: <div class="second-para"> <div class="container"> <div class="second-section"> <div class="c ...

Upload an image converted to `toDataURL` to the server

I've been attempting to integrate the signature_pad library, found at signature_pad, but I am struggling to grasp its functionality. Can someone guide me on how to retrieve an image value and send it to my server? Edit: I have experimented with dec ...

Exploring the array push method in ES6 destructuring

Is it possible to use something similar to the destructing assignment feature in ES6 to write cleaner code when pushing items into an array? I'm unsure how to implement it properly, especially within a context like Vue.js. Here is an example code snip ...

Building a follow/unfollow system in Node.jsLet's create a

I am relatively new to programming and I'm looking to implement a follow/unfollow feature in my application. router.put('/user/:id/follow', auth.verifyuser, (req, res)=>{ user.findById(req.params.id) .then((otherUser)=>{ if(otherU ...

How do I select the first element with class "cell" in D3, similar to jQuery's $(".cell:first")?

I have attempted this: d3.select(".cell:first") d3.selectAll(".cell").filter(":first") d3.selectAll(".cell").select(":first") but unfortunately, none of these methods are effective. ...

Presentation comparing ng-show and ng-hide efficiency

Introduction:- There may be some who opt to use ng-show instead of ng-hide="!true", while others choose ng-hide over ng-show="!true". Technically, the ng-hide directive is not necessary. However, Angular introduced it for a standard coding structure. Plea ...