What is the method for retrieving a class's property without creating an object instance?

Currently, I am working with a class setup like this:

class MyClass {
  constructor(privateInfo) {
    this.a = "a";
    this.b = "b";
  }

  myMethod() {
    return privateInfo;
  }
}

It seems that the privateInfo variable needs to be accessed, but it is not defined in the constructor.

Using private properties is not an option, as the property will be included in the stringified object which is not desired.

Is there a way to work around this? Any hints or suggestions would be greatly appreciated.

Answer №1

Using private properties wouldn't be effective because when the object is stringified, the property still appears in the string.

Actually, it does work:

class MyClass {
  #c;
  constructor(c) {
    this.a="a";
    this.b="b";
    this.#c=c;
  }
  myMethod() {
    return this.#c;
  }
}
const obj = new MyClass('hi');
console.log(JSON.stringify(obj));
console.log(obj.myMethod());

Another approach is to create the method within the constructor as a closure over the c variable:

class MyClass {
  constructor(c) {
    this.a="a";
    this.b="b";
    this.myMethod = () => {
      return c;
    };
  }
}
const obj = new MyClass('hi');
console.log(JSON.stringify(obj));
console.log(obj.myMethod());

Other solutions that work with regular properties and prevent them from being included in the JSON.stringify output include making the property non-enumerable or defining a custom toJSON method.

Answer №2

Utilizing the static Keyword :

Official MDN Explanation :

When it comes to static properties, they are not accessible directly on instances of the class. Instead, they are accessed on the class itself.

Static methods are commonly used as utility functions, like those for creating or duplicating objects. On the other hand, static properties are beneficial for caches, fixed configurations, or any other data that doesn't need to be duplicated across instances.

Illustrative Instance

class Student {
  name: string;
  static age: number;
  constructor(age: number) {
    this.name = 'John';
    Student.age = age;
  }
  static getAge = () => Student.age;
}

const student = new Student(20);

const json = JSON.stringify(student); // {"name":"John"}
console.log(json);
console.log(Student.getAge()); // 20

Your Implementation:

class MyClass {
  a: string;
  b: string;
  static c: string;
  constructor(c:string) {
    this.a = 'a';
    this.b = 'b';
    MyClass.c = c;
  }
  myMethod() {
    return MyClass.c;
  }
}
const obj = new MyClass('hello'); 
console.log(JSON.stringify(obj)); // {"a":"a","b":"b"}
console.log(obj.myMethod()); // hello

Answer №3

In my practical course, I introduced the attributes:

class MyClass{

  //other attributes
  preQ: string;
  postQ: string;

  constructor(data: InputData = { cli: cli.flags }) {
    Object.defineProperties(this, {
      preQ: { enumerable: false },
      postQ: { enumerable: false },
    });
    // other things
 }
}

As mentioned in the initial comment by Pointy. These attributes do not show up in the output of JSON.stringify.

These attributes are not meant to be transmitted to the server.

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

"The issue seems to stem from a snippet of compact JavaScript

I am facing an issue with a list item that contains both an image and text. The text is overlapping the image, but when I hover over the text, it disappears and only the picture is visible. Here is the HTML code snippet: <ul> <li><img ...

The node module.exports in promise function may result in an undefined return value

When attempting to log the Promise in routes.js, it returns as undefined. However, if logged in queries.js, it works fine. What changes should be made to the promise in order to properly return a response to routes.js? In queries.js: const rsClient = req ...

Accessing files for MongoDB cluster

My goal is to retrieve all the documents from a MongoDB cluster. Even though I have followed code examples from various online sources, I am encountering a minor issue. const MongoClient = require('mongodb'); const uri = "mongodb+srv://<user& ...

What's the reason behind ng-click only functioning with a function and not an assignment within this specific directive?

I am currently working on creating a dynamic table using an array of objects that can be sorted by clicking the headers. I have a specific question regarding how the sorting feature is implemented. let myDirectiveTemplate = ` <table class="directiveTab ...

Create a social chat platform similar to Facebook by implementing a chat box feature with the help of AJAX, jQuery

Currently, I have developed a chat box with two persistent issues. Despite my attempts to rectify them, I am unable to find a solution. Below, I will outline my code, focusing on the HTML section where the chat box, chat text area, and chat members are dis ...

I attempted to initiate a transition using JavaScript, but unfortunately it failed to execute

Hey there! I'm just starting out with HTML, CSS, and JavaScript, and I've been trying to make a transition work using JavaScript. The element I'm working with is a "menu-icon" which is a span tag with a small image nested inside another div ...

Inserting a line break in real-time within a JSX statement

Currently working on a React application that retrieves song lyrics from an API. The API provides me with a lyrics_body attribute as a string, which I use to showcase the lyrics on the webpage. However, when React renders it, the format is not ideal becau ...

Trouble with sending semicolons in Node.js MSSQL/MSNodesqlv8 database queries

Trying to create a simple API for interacting with a MSSQL v12 database using Nodejs. Successfully connected to the database with the mssql/msnodesqlv8 package, but encountering issues with parameterized queries. code: 'EREQUEST', number: 102 ...

Generate a Selectpicker dynamically when a button is clicked

Wanting to insert a new row in an HTML table dynamically by clicking on an add button. The new row includes a select element with the selectpicker class. Interestingly, when I remove the selectpicker class in my script to append a new row, the select eleme ...

Execute JavaScript using "matches" without the need for the page to refresh

I have been developing a school project which involves creating a Chrome extension to streamline the Checkout process on a website. In my manifest.json file, I specified that a content.js file should run when it matches a specific URL. "content_script ...

Using AJAX along with the append method to dynamically add identical HTML content multiple times to a single element

Although I have successfully implemented most of the desired functionality with this JavaScript code, there is a persistent bug that is causing unnecessary duplicates to be created when appending HTML. Detecting Multiples The problem lies in the fact tha ...

retrieving serialized object from an ajax request sent to the web server

As a newcomer to web development, I decided to create an ASP.NET project with a web API to test my skills. In the process, I crafted a controller and some JavaScript files as follows: Controller: namespace MyNamespace.Controllers { public c ...

Guide on organizing an array of objects by the sub-part of their property values

Is there a way to order the elements in the given array based on a custom criteria related to the last 3 letters of 'prop2' in descending order? The specific order should be 'ABR', 'FDE', 'ZFR'. Another array needs t ...

Incorporating Vue into a dated website by eliminating the div and replacing it with new dynamic Vue components

As I attempt to integrate Vue into my old website, I want the existing jQuery scripts to continue functioning and the old HTML content to be displayed. However, I am encountering an issue where the el element and its contents are being removed. This probl ...

Automatically navigate to the bottom of the page by applying the overflow auto feature

I've been working on a chat application using Vue.js. I have set the overflow property to auto for my div element. My goal is to automatically scroll to the bottom of the div so that users won't have to manually click the scrollbar to view the la ...

To properly document the results, I must utilize a button to record the identification of a specific color

I'm working on a code that creates a clickable box which changes colors from black to green to white by going through different shades of green whenever the mouse is clicked. What I now need to do is implement a feature that displays the current shade ...

The compression feature in express.js middleware is not functioning correctly

The middlewares set up in my app are as follows: app.use(express.favicon(__dirname + '/static/public/images/favicon.ico')); app.use(express.compress()); app.use(express.json()); app.use(express.urlencoded()); app.use(express.cookieParser('S ...

Interactive Content Swapping: How to Use Javascript for Dynamic Link Updates

http://jsfiddle.net/bUjx7/42/ <script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'> </script> <script type='text/javascript'> $(document).ready(function () { $('.fieldreplace ...

Ember.js alternative for Angular's filter for searching through ng-models

Looking for an easy way to implement a search filter similar to Angular? <input type="text" ng-model="resultFilter" placeholder="Search"> <ul> <li ng-repeat="result in results | filter:resultFilter">{{result.name}}</li> </u ...

Exporting JSON blend files in Three.js is causing an error that says "Cannot read property 'type' of undefined."

Trying to display the default 3D cube template from Blender v2.74 in Chrome browser, I exported it as json using the threejs v1.4.0 add-on and I'm using Three.js revision 71. Referencing the documentation at , I attempted to load this json model stor ...