What causes the data in my JavaScript class to be undefined when I call it from a component?

In my external JavasScript file (sun.js), I have a class structured like this :

export default class Sun {
   constructor(){
      this.text = 'I\'m shining!';
   }
    
    static testIfShining() {
       console.log("is the sun shining?");
       console.log(this.text);
    }
 }

I've imported this class into one of my components

import Sun from '../sun.js'

Then, I invoke the testIfShining() function within the mounted lifecycle :

mounted() {
   Sun.testIfShining();
}

When I check my console, I see the following log message:

is the sun shining?
undefined

The function is functional, but the value of this.text is displaying as undefined.

How can I access the value set in my constructor across different functions in the class? I want the data to act like an attribute so that it can be reused effectively.

Answer №1

Ensuring your code is properly formatted is important, especially when dealing with special characters like single quotes. For example:

 this.text = 'I\'m shining!';

Make sure to escape the single quote in your code just like that.

export default class Sun {
   constructor(){
      this.text = "I'm shining!"; // Remember to also use double quotes
   }
    
   testIfShining() { 
       console.log("is the sun shining?");
       console.log(this.text);
    }
 }

Quick tip: Also structure your code like this for better readability:

Would you consider implementing it this way?

mounted() {
   let sun = new Sun();
   sun.testIfShining();
}

To see an example in action, check out this demo: https://jsfiddle.net/y4675twv/2/

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

Every time I attempt to compile NodeJS, I encounter a compilation error

Within mymodule.js var fs = require('fs') var path = require('path') module.exports = function(dir, extension, callback){ fs.readdir(dir, function(error, files){ if(error) return callback(error) else { ...

I seem to be overlooking something. The calculation is not displaying in the designated field

Having trouble with my area calculator - the area field is not updating as expected when I enter numbers in each field. Any advice on what might be missing? function calculateArea() { var form = document.getElementById("calc"); var sLength = parseFl ...

Exploring the capabilities of rowGroup within DataTables

Currently, in the process of completing a project, I am retrieving data from a REST API to populate my DataTable. To avoid displaying duplicate items, I am interested in creating subrows in the DataTable with a drop-down menu based on an item in the "Deliv ...

Steps for adding a cover over an image (not utilizing clip-path, but the reverse approach)

I am currently exploring how to create a div with a mask that allows me to see through it to reveal a background image. Most tutorials I find discuss clip-paths, but what I am seeking is the opposite of this concept. Clip-paths typically display what is in ...

What strategies can be used to ensure that the page layout adjusts seamlessly to even the smallest shifts in window size?

Of course, I am familiar with media queries and how they allow us to set specific min-width and max-width ranges for CSS changes. However, when I look at the website styledotme.com, I notice that the block/div beneath the navigation bar gradually shrinks ...

Creating dynamic URL routes for a static website using Vue

I am facing a challenge with my static site as I am unable to add rewrites through htaccess. Currently, our site is built using Vue on top of static .html templates such as \example\index.html. When I want to create a subpage within this layout, ...

Change elements in real-time

I have a requirement to adjust elements with the class .super-elem by adding an attribute adjusted="true". Initially, I can easily achieve this within the document's ready event : $(".super-elem").attr("adjusted", "true"); However, I may add more . ...

What could be causing Firebase serve to malfunction while Firebase deploy runs smoothly?

Every time I run firebase deploy, it successfully creates data. But when I run firebase serve, it always ends up in the catch function! This is the function I'm working with: exports.createUser = functions.https.onRequest((req, res) => { const ...

Tips on creating a unique d3js tree design

I am a beginner when it comes to d3js and javascript in general. My goal is to create an interactive IP administration overview using d3js by modeling json data. I know that the key tool for this job is likely d3.layout.tree, which will provide me with the ...

Customizing the default element color in vue-bootstrap: A step-by-step guide

One issue I am currently facing is in my b-table, where I have a function that colors the rows based on a specific property: <template> <b-table sticky-header="70vh" bordered striped :items="logs" :f ...

AngularJS Controller failing to populate data

The following code snippet is designed to run on a SharePoint Web Part page within a Script Editor web part. It executes an AJAX call to retrieve list items from SharePoint and should then populate a form with the fetched items. However, no action seems ...

The type unknown[] cannot be assigned to type React.ReactNode

import * as React from 'react'; import { List, ListItemButton, ListItemIcon, ListItemText, ListItem} from '@mui/material'; import LightbulbOutlinedIcon from '@mui/icons-material/LightbulbOutlined'; import NotificationsNoneOutl ...

When hovering over an object in three.js, the cursor should change on mouseover

In my scene, I have added a sphere and plane geometry. Clicking on the plane geometry will open a linked website. Now, when hovering over the plane geometry, I want the mouse cursor to change to a hand pointer icon, and revert back to its original style ...

What is the best way to create a Type for approved image formats?

I've been tasked by the client to create a list of supported icon names using TypeScript. However, as a newcomer to TypeScript, I'm finding it challenging to accomplish this. Here is my SVG component containing over 100 SVG icons. CustomIcons.t ...

Tips for integrating NanoHTTPD with AJAX requests

I am currently working on setting up NanoHTTPD on an android device to respond to AJAX requests in a way that the requesting javascript can understand the response. Here is my implementation of the NanoHTTPD serve method: public NanoHTTPD.Response serve( ...

Encountering issues with manually altering routes in Vue.js 3

After creating a Vue.js application, I decided to host it on two different websites - vercel.com and netlify.com since I do not have my own domain. The code runs smoothly, but whenever I manually attempt to change a route by modifying the URL, a '404 ...

Assigning a Node.js exported function to a variable

Is there a way to save an exported function as a variable without executing it right away, in order to use Promise.all? I noticed that when I assign the function to a variable, it automatically runs. How can I prevent this from happening during assignment? ...

Having trouble locating elements that "match this specific selector" using jQuery's `.find()` method?

According to the jQuery documentation, the find function filters elements based on whether they match a given selector. This sentence may not be completely accurate, or I might be misunderstanding its meaning. For instance, when attempting to change the ...

Transforming a JavaScript variable into a PHP function call

Looking to transfer a Javascript variable into PHP by replacing the const 4 with var i var ntime = '<?php echo count($czasAr);?>'; for (var i = 0; i < ntime; i++) { ...

Handle clicking on a mesh

I'm currently working on implementing a click event for a mesh (cube) in order to perform some processing tasks. var cubeFor3D = new THREE.Mesh(new THREE.CubeGeometry(40,80,40),img3D); scene.add(cubeFor3D); // renderer.render(scene,c ...