The peculiar actions of ECMAScript6 classes

I have encountered strange behavior in the output of my ES6 program in WebStorm. I am using Babel to transpile the code. Can someone help me understand what's going on?

class DateLocationValidator{
    _appointments;
    constructor(appointments){
        this._appointments = appointments;
        console.log(this._appointments);
    }

    validate(appointmentViewModel)
    {
        console.log('validating');

        if(this._appointments==null || this._appointments.length==0) {
            console.log('appointments null');
            console.log(this._appointments);
            return {
                outcome:true,
                reason:'',
                conflictId:0
            };
        }else{

            console.log('appointments not null');
            var result = this._appointments.where(function(appointment)
            {
                console.log('searching');
                if(appointment.startDate==appointmentViewModel.startDate && appointment.startDate==appointmentViewModel.startDate){
                    console.log('found');
                    return true;
                }
            });

            if(result.length>0){
                return {
                        outcome:true,
                        reason:'There is already an appointment scheduled for this location on this date',
                        conflictId:result[0].id
                };
            }
        }
    }
}

Below is a test scenario:

it("Fails when appointment clashes exactly",function(){
        try {
            let appointments = [new AppointmentViewModel(1, new Date(2015, 1, 1), new Date(2015, 1, 2))];
            let validator = new DateLocationValidator(appointments);
            let appointmentViewmodel = new AppointmentViewModel(1, new Date(2015, 1, 1), new Date(2015, 1, 2));
            let result = new validator.validate(appointmentViewmodel);
            expect(result.outcome).toBe(false);
        }
        catch(excep){
            console.log(excep)
            expect(true).toBe(false);
        }
    });

'appointments null' message gets printed even after the array has been correctly initialized in the constructor.

Additionally, attempting to call a function from validate results in an undefined error. Can anyone provide assistance?

Thanks, M

Answer №1

It appears that there was an error in your code where you mistakenly used the validate function as a constructor. Make sure to remove the unnecessary new keyword!

let result = validator.validate(appointmentViewmodel);
//           ^^^

If this were true ES6 (not transpiled), it would have generated an exception, since functions defined using method syntax cannot be invoked with new (they lack a [[construct]] property).

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

What is the best way to create separate arrays for every element in my object, containing a total of four arrays to efficiently produce a weekly forecast?

Hey there, I'm back with an update on my ongoing project. I've encountered a major challenge while trying to incorporate a 7-day forecast display in my app. Something along these lines: https://i.stack.imgur.com/xJA4M.png https://i.stack.imgur. ...

Cordova triggers a 500 (Internal Server Error) when making an Ajax request

When I send an ajax request, it works fine in the browser but returns an internal error when sent within a Cordova APK. Upon comparing the headers, I noticed that the only difference is in the ORIGIN: The one not working has origin: file:// POST 500 (In ...

Is there a way to redirect header menu items to an external URL instead of an internal file in React/Gatsby?

Struggling with modifying a react Gatsby template where I need to redirect a header menu item to an external URL while keeping the other menu items intact. The Header file has nested files like: Header.js Index.js menuItems.js The behavior is contro ...

Tips for sending a multipart/form-data request using AJAX

I am facing an issue with the function below. I need to upload multiple files and submit a request via ajax. The content type is currently set as "text/plain;charset=UTF-8" but I want to change it to "multipart/form-data". Can anyone provide suggestions ...

Error loading code. Works when manually pasted, but not when executed with JavaScript

After some trial and error, I found that this code works perfectly if I manually copy the content from the class isotope in 1.php to the class grid on this page. However, when I try to use JS to do the same thing, it mysteriously stops working. Any sugge ...

I am not encountering any error messages, but when I attempt to click on the form, the mouse cursor does not change to the expected form type

While there are no errors showing up in the Chrome Developers Error code, I am facing an issue with my form where the text fields are not visible. It should be a simple task, but it has turned into a headache for me. I would greatly appreciate any help i ...

Tips for extracting and utilizing the values of multiple checked checkboxes in a jQuery datatable

When a button is clicked, I am trying to retrieve the selected values of multiple rows from the datatables. However, with my current code below, I am only able to get the value of the first selected row. function AssignVendor() { var table = $(assig ...

Creating a prototype function in JavaScript

I am attempting to create a JavaScript prototype function that replicates the Python syntax of 'a' in 'abc'. The function works correctly in one example, but not in another. Can you help me identify what mistake I made? String.proto ...

What is the purpose of <form/> element if AJAX exists?

I recently embarked on the journey of learning JavaScript, and I quickly discovered that AJAX could be a powerful alternative to using forms in my projects. Here's a simple comparison: <form id="demo_form" action="demo" method="post"> < ...

Error encountered on Next.js boilerplate development server

As I embark on my journey to learn next.js, I decided to install create-next-app and attempted to start a development server without making any changes to the boilerplate code provided. However, I encountered the following error: ./styles/globals.css Globa ...

How can you display directions while using the Google Maps app in a React Native application?

I need assistance with rendering directions between two points (current location and a passed location). Currently, I am using Linking to open the Google Maps App. However, when clicking the button passing the (latitude, longitude), I want the map to disp ...

Error in NodeJs: ReferenceError - the variable I created is not defined

Encountering an issue while attempting to use a module in my router file. I have successfully required it, but now I am seeing the following error message: ReferenceError: USERS is not defined at c:\work\nodejs\router\main.js:32 ...

Ways to implement modifications in child component through parent?

In my Angular application, I have a file upload feature where the file upload component is a child component and the app component serves as the parent component. The app.component.html (Parent) contains a single line of code that calls the child componen ...

React Native for Android Build Not Progressing

info Running jetifier to migrate libraries to AndroidX. You can disable it using the "--no-jetifier" flag. Jetifier has identified 967 files for forward-jetification. Utilizing 4 workers... info The JS server is already operational. * A daemon is not runni ...

What is causing the jQuery selector to only return one element instead of both?

I've encountered a scenario where I am generating a jQuery object from an HTML string and need to target all elements within it with a specific class. What I find interesting is that it returns different results based on the type of selection method ...

The AJAX POST function is not functioning properly when clicking on contextmenus

Can someone please assist me? I am having trouble sending data via ajax post to my nodejs server from contextmenus. It is not functioning as expected. Although the ajax request does not give any error alert, the data is not being sent successfully. I hav ...

Tips for optimizing the placement of div elements for top advertisements on Amazon's website

I'm looking to overlay some divs on top of Amazon.com ads, similar to the image above. This is part of a personal project where I need to position these divs precisely over the ads. To achieve this effect, I've been using getBoundingClientRect t ...

Exploring the art of group rotation in Three.js

My dilemma involves two box geometries: var box; loader.load( 'img/plytos.jpg', function ( texture ){ var boxGeometry = new THREE.BoxGeometry(7,0.5,0.5); var boxMaterial = new THREE.MeshLambertMaterial({ map: texture, overdraw: 0.5 }); box = ne ...

Guide on how to lock header table in datagrid with EasyUI and JQ

The order listing is displayed in a table format like this: <div class="datagrid-header"> <div class="datagrid-header-inner" style="display: block;"> <table class="datagrid-htable" border="0" cellspacing="0" cellpadding="0" style="height: ...

Only apply prevent default on specific levels for better control

I am currently working on a menu with submenus. I am facing an issue where when I click on a top-level menu item, I need to use prevent default because they are anchor tags. However, for the submenu items, I do not want to prevent default behavior. I am st ...