Is it possible for me to define a constant that applies to the entire application

Can I ensure a class exists only once and share that instance with other classes by explicitly passing it to each constructor (method 1) or by instantiating it once and exporting the variable (method 2)?

// foo.ts (the shared class)
class Foo {
  // ...
}

Method 1:

// bar.ts (one of the classes using Foo)
class Bar {
  constructor(foo: Foo) {
    // ...
  }
}

Method 2:

// a file containing the instantiation (how to name it?)
import {Foo} from './foo';

export const foo = new Foo();
// bar.ts
import {foo} from './theFileContainingTheInstantiation';
class Bar {
  // use foo
}

While global variables are not recommended, I find method 2 much more efficient as it eliminates the need to add an argument to each class constructor and guarantees a unique instantiation without requiring careful handling in every class.

Answer №1

Utilize the read-only property feature

export class Foo {
    readonly myReadOnlyProperty = 1;
}

Ensure to export it and then access it like this

import {Foo} from './foo';
var cfoo = new Foo();
console.log(cfoo.myReadOnlyProperty) // 1

You can also import classes. Export foo first and include some test methods

export class Foo {
    readonly myReadOnlyProperty = "Say";
    hello() {
        return "Hello,";
    }
}

In your file that requires foo, extend the class as follows

import {Foo} from './foo'; // importing foo from another file
class Bar extends Foo { // extending foo with a new class to inherit its methods
  world(){
    let val = this.hello(); // accessing foo's methods here
    console.log(this.myReadOnlyProperty + " " + val + " world"); // Say Hello, world
  }
}
let funct = new Bar();
funct.world(); // execute it

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

Exploring JSON data hierarchies with AngularJS using ng-options

In my web app, I am utilizing AngularJS to create two dropdown lists using ng-options. The first dropdown displays a list of countries The second dropdown provides language preferences for the selected country As I am still new to AngularJS, I am able t ...

Encountering an issue while attempting to transmit Electron window data

Hey there! I'm currently in the process of transitioning my project from a web browser to a GUI-based app using electron. I came across this video which was really helpful in getting started. The tutorial uses yarn, but I prefer npm 9.2.0. Initially, ...

Dive | Loading page (with built-in timeout) preceding website launch (portfolio)

I'm currently working on building my own portfolio website using NextJS, and I am looking to implement a short splash screen that only appears for 3-5 seconds on first visit and is shown only once per user. Any suggestions on how I can achieve this? : ...

Enhancing a node.js application with express()

I am currently utilizing Express MVC with node.js. The primary object I am working with is express(), which is assigned to an alias called app: var express = require('express'); app = express(); Is there a way for me to expand the functionali ...

Invoke the subscribe function within the encompassing parent function

In crafting a versatile method, I have devised the following code snippet: fetchArticle(loading: Loading): void { this.articleService.getArticleById(this.data.definition.id) .map((response: any) => response.json()) .subscribe((response: ...

The URL for the form action does not match the URL of the current page

Issue: I'm encountering an issue with a form where the form action URL is different from the page URL where the form is located. Page URL = www.page.com Form action = "" Problem: After submitting the form, it redirects to the form action URL inst ...

GatsbyJS - Leveraging SVGs for Creative Background Effects in CSS

I've been experimenting with something for a while now, and I need some advice on a project I'm working on in Gatsby. I'm attempting to use SVGs as pseudo background images, but so far it's not working for me. Here is the SCSS code sn ...

Performing an AJAX request when leaving the page

I'm currently developing a website with various links to external sites. My goal is to send an ajax call to notify the server when a user clicks on one of these links and navigates away from the page. I've implemented an alert on link click, whic ...

Is there a way to track the loading time of a page using the nextjs router?

As I navigate through a next.js page, I often notice a noticeable delay between triggering a router.push and the subsequent loading of the next page. How can I accurately measure this delay? The process of router push involves actual work before transitio ...

Ensuring the length of an array meets security requirements in Firebase rules

Can the votes array be restricted to exactly 5 entries? Checking if newData.child('votes').val().length === 5) doesn't work because the length property only applies to strings. Here is a sample of my data: votes $voteID page:"12345 ...

Unusual HTML Structure (content misplaced or out of order?)

Recently, I started learning CSS/HTML in school and we just delved into Javascript. Currently, we are working on a website project. However, while trying to integrate the content with the navbar, I encountered a strange issue. When resizing to 620px or le ...

Unraveling HTML elements within a string using MongoDB: A step-by-step guide

Currently, I am in the process of creating a blog from scratch as a way to enhance my skills. The posts' content is stored as a long string in MongoDB with some random HTML tags added for testing purposes. I am curious about the conventional method fo ...

Streamline the ngClass conditions when using ngFor loops

My array consists of 5 string values: excited, happy, neutral, sad, angry. To simplify my HTML and avoid repeating code for each value, I am utilizing ngClass and ngFor. The challenge I'm facing is that the ngClass statement is quite lengthy, and I& ...

Transfer the cropped image to the database through AJAX on the client side and PHP on the server side

I am attempting to upload an image to a Database using JavaScript on the client-side and PHP on the server-side. The first step is selecting an image from the gallery. After zooming and cropping the image, it should be passed to the database. The issue ...

The Express server's `GET` request at the root does not seem

When I access localhost:8080/chat?k=1&d=1, the console displays "CHAT PAGE" and everything works correctly. However, when I try to visit localhost:8080, the root event does not display "INDEX PAGE" as expected. Instead, it automatically retrieves ind ...

The callback for fs.WriteFile is triggered before the file is written to disk

I am encountering an issue with my express request callback that involves writing a file after calling a callback function. zip.addLocalFolder(`/path/to/folder`, `./`); var data = zip.toBuffer(); fs.writeFile(`path/to/download.zip`,data,function (err) { ...

Is the indigo-pink color scheme fully implemented after installing @angular/material and scss using ng add command?

After running ng add @angular/material, we are prompted to choose a CSS framework and theme. I opted for indigo-pink and scss. Will the material components automatically inherit this theme, or do we need to take additional steps? When using normal CSS (wi ...

JavaScript's Use of Brackets

I’ve been working on a new project that involves adding links. To do this, users can input both the link URL and the text they want displayed. I used a prompt to gather this information. Here’s the code snippet I wrote: document.getElementById(ev.targ ...

Is Ajax capable of processing and returning JSON data effectively?

I am in the process of making modifications to my codeigniter application. One of the changes I am implementing is allowing admin users to place orders through the admin panel, specifically for received orders via magazines, exhibitions, etc. To achieve ...

Guide on adding a JavaScript array to another array in Angular

In my Angular component, I encountered an issue with a variable called jsonArray:any not being recognized in the template. The error message indicated that it was undefined. import {Component, NgModule} from '@angular/core' import {BrowserModule ...