ES6 syntax causes import class function to malfunction

I'm having an issue while trying to import and initialize a class in ES6. When I run the code, the console displays an error message stating 'undefined property hej'.

Work.js

class Work {

    constructor() {

    }

    hej() {
        alert('hej');
    }
}

export default Work;

Main.js

import Work from './modules/work.js';


Work.hej();

What could be causing this error? Any suggestions on how to resolve it?

Answer №1

Your Task function does not have a hey property. The hey property belongs to the prototype that would be assigned to an instance of New Task, so:

const t = new Task();
t.hey();

Alternatively, if you prefer to use it as Task.hey();, make it static:

class Task {
    static hey() {
//  ^^^^^^-----------------
        alert("hey");
    }
}

Now, Task.hey() will work because hey is a static method (a method of Task, not of instances of Task).


If you try using this plunker on the latest version of Chrome, it should demonstrate that it's functioning with an instance method. Here are the source files:

index.html:

<!DOCTYPE html>
<html>

  <body>
    <script type="module" src="task.js"></script>
    <script type="module" src="app.js"></script>
  </body>

</html>

task.js:

class Task {
    constructor() {
    }

    hey() {
        document.body.appendChild(
          document.createTextNode("hey")
        );
    }
}
export default Task;

app.js:

import Task from './task.js';

const t = new Task();
t.hey();

If you use this one on the most recent version of Chrome, it'll show that it's working (with a static method). Here's the source:

index.html (same as above)

task.js:

class Task {
    constructor() {
    }

    static hey() {
        document.body.appendChild(
          document.createTextNode("hey")
        );
    }
}
export default Task;

app.js:

import Task from './task.js';

Task.hey();

Please note that module support in Chrome is very new; you must have the latest updates installed (as of late October 2017).

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

How can I use AJAX to remove {{$key}} in Laravel?

In our codebase, we are utilizing multiple hidden inputs within a loop structured like @foreach. <form action="{{ route('parties.updateAndCreate', auth()->id()) }}" method="post"> @csrf @method('PUT' ...

Pick Control - Utilize jQuery to display options that haven't been chosen before

Seeking assistance with a table view that includes a button for dynamically adding new rows. Each row contains a select control. Using Select2 for styling purposes. How can I ensure that when adding a new row, the select options only display those not prev ...

Tips for dynamically inserting a new column into a table at any position other than the beginning or end

I have created a dynamic table where rows and columns can be added dynamically. However, I am facing an issue where I am unable to add a new column between the first and last column of the table. Currently, new columns are only being added at the end. $ ...

Using traditional JavaScript, bring in a class from Node.js

I have a mix of files utilizing the Node.js framework and others that I'd like to incorporate without it. When attempting to import a class from my Node files, where module.exports was used, into my JavaScript files, I encounter an error stating "the ...

Enhance PHP search functionality by showcasing hidden auto-complete suggestions in real-time

I am attempting to showcase unlisted search results that can be clicked on to redirect the user to a specific HTML page based on data retrieved from a MySQL database. My development environment is PhoneGap. Thus far, I have successfully set up a basic PH ...

Is it possible to create a dynamic HTML element with an AngularJS Directive without using $scope?

Looking to use This Plunker example code to dynamically add elements to an HTML page using AngularJS. (Make sure to run it in a separate link, not in the editor environment.) This will be my first time working with AngularJS Directives (aside from simple ...

Having trouble retrieving JSON response from URL with javascript

I've been struggling to retrieve a JSON response from the Kraken API for currency conversion. Despite trying various methods, including those from sources like cryptonator and Yahoo, I haven't had any success with Kraken's API. The URL appea ...

Receiving a Promise<fullfield> as a result

I have a situation where I am adding several promises to an array: const apiCallsToMake = []; apiCallsToMake.push(this.getDataFromUnsplash(copyInputParams)); apiCallsToMake.push(this.getDataFromPexels(copyInputParams)); apiCallsToMake.pu ...

Preventing CSRF attacks using AJAX in a Django application

After some troubleshooting, I discovered the mistake in my HTML code. Simply adding {% csrf_token %} resolved the issue :) Big thanks to everyone who helped! (I followed the JavaScript snippet provided in the initial response but I'm still encounte ...

Issues with sending data using ajax

Trying to get weinre working through Ajax by calling this on dom ready: $.ajax({ url: 'http://debug.build.phonegap.com/target/target-script-min.js#hutber', dataType: "script", crossDomain: true, error: function(data){ c( ...

Use Angular to change the style of multiple element groups at the same time when hovering

When hovering over an element with a common attribute, such as a class name, I want to change the style of all elements that share that attribute. Achieving this effect is simple with jQuery: $(function() { $('.bookId4').hover( function(){ ...

Troubleshooting Bootstrap bug caused by rollupPluginBabelHelpers

I am currently working on a Bootstrap 4 website. I noticed that in Internet Explorer, the modal works fine when opened for the first time, but then displays an error in the console and does not open when trying to do so a second time on the same window. On ...

Incorporate audio playback on image click using JavaScript, with the feature to automatically pause the playback if multiple images are playing simultaneously

<img class="cl" src="photo/198.jpg"/></br> <audio class="cs" controls> <source src="audio/198 banu nagamothu.mp3" type="audio/mpeg"> </audio> I prefer not to have audio controls initially, but when the image i ...

Express error handling lacking clarity

My application has a route dedicated to accepting file uploads: Here's a snippet from app.js ... var upload = require('./routes/upload'); ... app.use('/upload', upload); ... ... /* It is essential to start the application with ...

Connecting UserIDs with Embedded Documents in Mongoose

My goal is to connect individuals with each other by embedding a Match document in the user's matches array. This is my User Model: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const Match = new Schema({ with: ...

Is there a way to retrieve the value from a moment-formatted date picker in the (YYYY-MM-DD) format?

I have a Vue application with a datepicker from Ant Design Vue that is returning the following moment object: Moment {…} _d: Thu Oct 24 1996 00:00:00 GMT+0800 (Malaysia Time) _f: "YYYY-MM-DD" _i: "1996-10-15" _isAMomentObject: (...) _isUTC: (...) _isVal ...

Issue with Webpack - npm run start and build operation not functioning?

Although I typically use create-react-app for my React projects, I decided to create one without it. However, I am encountering issues with the webpack configuration as I am not very familiar with it: This is how my package.json file looks like: { " ...

Unable to retrieve data list in Angular TypeScript

After sending a request to the server and receiving a list of data, I encountered an issue where the data appears to be empty when trying to use it in another function within the same file. The code snippet below initializes an array named tree: tree:any ...

Save the current time and date to a database by executing a mysql_query

<form action="actionMAppointment.php?stu_id=<?php echo $row_RecEdit['stu_id'] ?>" method="post"> Time: <input type = "time" name="appointmentTime" id = "appointmentTime" /> Date: <input type = ...

What methods can be used to broaden configuration variables within VSCode using an extension?

I attempted to develop an extension for vscode that requires reading the pasteImage.parth variable from the ./vscode/settings.json file { "pasteImage.path": "${workspaceRoot}/assets/images" } In my attempt to retrieve the variable us ...