What is the correct way to invoke a function contained within an object that is stored in an array?

I've encountered a problem with my program. I'm attempting to invoke a function that is part of an object stored in an array, but I'm having difficulty calling the function correctly.

//Initialize Array for Storing Projects
let allProjects = [];

//Define Parent Class for Creating Project Objects
class Project {

    constructor(projTitle, projDescription, projHours, projReserved) {

        //Declare variables
        this._name = projTitle;
        this._description =  projDescription;
        this._hours = projHours;
        this._reserved = projReserved;

        //Add newly created object to array
        allProjects.push(this);

        //TODO Reserve function
        function reserve() {
            if (this._reserved === false ) {
                this._reserved === true;
            } else {
                console.log('The project you are trying to reserve has already been taken.');
            }
        }
    };
}

//Invoke the reserve function of the object at index 0 in the array.
allProjects[0].reserve();

Upon running the program, I encounter the following error:

allProjects[0].reserve();
           ^
TypeError: allProjects[0].reserve is not a function

Any assistance or advice would be highly appreciated.

Answer №1

If you would like the reserve function to be callable on the instantiated object, it should be placed on the prototype. Remember, === is for comparison, not for assignment; make sure to change

this._reserved === true;

to

this._reserved = true;

In its entirety:

class Project {
  constructor(projTitle, projDescription, projHours, projReserved) {
    this._name = projTitle;
    this._description =  projDescription;
    this._hours = projHours;
    this._reserved = projReserved;

    allProjects.push(this);
  }
  reserve() {
    if (this._reserved === false ) {
      this._reserved = true;
    } else {
      console.log('The project has already been reserved.');
    }
  }
}

An alternative approach that is technically correct but not very efficient (which might have been your original intention) would involve assigning the function to the instantiated object's reserve property within the constructor:

class Project {
  constructor(projTitle, projDescription, projHours, projReserved) {
    this._name = projTitle;
    this._description =  projDescription;
    this._hours = projHours;
    this._reserved = projReserved;

    allProjects.push(this);
    this.reserve = function() {
      if (this._reserved === false ) {
        this._reserved = true;
      } else {
        console.log('The project has already been reserved.');
      }
    }
  }
}

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

Preview functionality is disabled in the iOS share extension

Currently, I'm developing a share extension for Safari on iOS. Our approach involves utilizing the default UI provided by iOS and extending the SLComposeServiceViewController class. In addition to this, I have incorporated a JavaScript function to ext ...

Connecting via web sockets through SSL is not functioning properly

My Web Socket functions correctly in both the localhost and production environments (https://www.example.com). However, upon deploying the same code to the pp environment (), I encounter the error message: WebSocket handshake - Unexpected response code: 4 ...

Is it true that by utilizing Vue's v-for, every line of HTML code becomes a

I'm struggling to utilize v-for in order to create multiple div elements, but no matter how I attempt it (even trying to iterate over a list), the v-for doesn't seem to function properly and always turns the line into a comment when executed. No ...

Encountering issues with scope: Unable to retrieve value and receiving an error message stating 'Cannot assign value to undefined property'

var mainApp = angular.module("Main", []); mainApp.controller("CtrlMain", [ function ($scope) { $scope.amount = 545 }]);` var app = angular.module("Main", []); app.controller("MainCtrl", [ function ($scope) { $scope.value = 545 ...

Utilizing React Router with Material-Table for Efficient Column Value Filtering

Is there a way to dynamically pass Route params into the filtering fields of a React table component? I am currently utilizing the material-table component and have a list of links structured like this: <ul> <li> <Link to="/Products/ ...

What steps can be taken to address the build problem with Angular version 13?

Encountering a problem while working with Angular 13: https://i.sstatic.net/CbAUhh6r.png Attempting to build using ng build --configuration=test, however facing errors as mentioned above. Interestingly, if I remove the reference to bootstrap.min.css in t ...

The system couldn't locate the module: Issue: Unable to find module 'fs' within the directory

I am currently working on integrating the ADAL JS sample code from this link into a SharePoint framework client web part. My code is fairly straightforward, as I have already installed packages like adal, fs, and node-fs using NPM. However, when running t ...

PHP issues caused by Ajax form compatibility

I'm currently working on developing an upload website and I've encountered some challenges while trying to implement an upload progress bar. The Ajax form in my scripts seems to be causing issues with the PHP code, preventing the file from being ...

Updated Multer version causing issues with uploading image files

After using multer middleware to upload an image, I encountered an issue where the file image was showing up as undefined. This meant that I couldn't retrieve the name or file extension of the uploaded file. I'm not sure if this is an error with ...

Modifying SASS variable values based on the presence of specific text in the page URL

How can I utilize the same SASS file for two different websites with similar functionality but different color schemes? My goal is to dynamically change the color based on the URL of the page. However, I am facing challenges in extracting the page URL from ...

Discovering parent elements far up the DOM hierarchy using jQuery

I'm a bit confused about how to locate an element that is a parent element further up the tree. $('.btn-action').hover( function(){ $(this).find('.product-card').addClass('animated bounce'); }, function(){ ...

After a two-second period of inactivity, the buttons on the item should trigger an action

I have a scenario in mind that I want to implement: When the user clicks on either the "Plus" or "Minus" button. If the user doesn't click on any of those buttons within 2 seconds, then we assume that the current quantity should be sent to the server ...

Exclude the key-value pair for any objects where the value is null

Is there a way to omit one key-value pair if the value is null in the TypeScript code snippet below, which creates a new record in the Firestore database? firestore.doc(`users/${user.uid}`).set({ email: user.email, name: user.displayName, phone: ...

Looking to pass two distinct variables using a single props with v-if in Vue-JS. Any suggestions?

I am attempting to pass different data to my other component. Essentially, when my variable firstvalue is not null, I want to send firstvalue. Currently, this setup is functioning as expected. However, I now wish to send secondvalue if it is not null. < ...

Interpolating backticks in Javascript allows for constructing a URL containing empty spaces

When utilizing string interpolation with backticks to construct a URL that sends data to a django endpoint, the resulting URL contains unnecessary whitespace and a new line. The problematic JavaScript code is as follows: (function (window, document, unde ...

Delegate All Events to the Document

In my current setup, I have over 350 events that look like: $(document).on('click','.removable-init',function(){}); I've noticed a performance issue where some click events are delayed by a fraction of a second. This is happening ...

Exploring Angular 9: Harnessing the Power of Fork Join with an Array of

I have a challenge where I need to send multiple API requests to an endpoint by iterating over an array of values To handle this, I decided to use rxjs library and specifically the forkJoin method //array to keep observables propOb: Observable<any>[ ...

Utilize AJAX to update the database through a bootstrap modal interface

My current project involves creating a webpage to display database records with edit buttons that trigger bootstrap modals for user input and status changes. The goal is to use AJAX to update the database with any modifications made. However, I'm enco ...

Leverage object properties as data table field values in VueJS

In my current project, I am utilizing VueJS (version 2.5.9) to display and modify data tables within an administrative application. Initially, I used a basic Grid component for the data table, following an example provided here. However, I came across an e ...

Using XMLHttpRequest with gzip compression

Utilizing the request module in node.js makes it simple to create a request that can retrieve and correctly decompress compressed data from the source: var request = require('request'); var requestOptions = { url: 'http://whatever.com/g ...