Obtain an object or function name using JavaScript

In the process of developing a JavaScript app, I am utilizing a third-party library which defines an object in the following structure:

getLibrary().SomeObject = function() {
  function SomeObject(attrs) {
    this.id = attrs.id;
    this.description = attrs.description || '';

    this.result = {
      id: this.id,
      description: this.description,
    };
  }

  SomeObject.prototype.doSomething = function(actual) {
    return 'do something';
  };

  SomeObject.prototype.calculate = function() {
    return 42;
  };

  return SomeObject;
};

I have created an instance of this object stored in a variable named myInstance. When reviewing the Chrome console output using console.log(myInstance), the displayed content is as follows:

v SomeObject
  id: '1'
  description: 'my description'
  > result: Object

My objective is to extract the "SomeObject" part from the output above. Attempting to use the instanceof check with SomeObject did not yield the desired outcome. Essentially, I am seeking a way to retrieve the name of the "type" or function associated with myInstance.

Any assistance on how to achieve this would be greatly appreciated.

Answer №1

getLibrary().SomeObject is not just a regular constructor function, it's actually a function that returns a constructor function. So in order to use it correctly, you would need to do something like the following:

var SomeObject = getLibrary().SomeObject();
// Remember to add the parentheses at the end ^^^

This way, you are calling the function to obtain the constructor function it returns.

Once you have the constructor function, you can create an instance using it:

var myInstance = new SomeObject({id:"some_id"});

By doing this, the instanceof operator will work as expected:

console.log(myInstance instanceof SomeObject); // true

Live Example:

var library = {};
function getLibrary() {
    return library;
}
getLibrary().SomeObject = function() {
  function SomeObject(attrs) {
    this.id = attrs.id;
    this.description = attrs.description || '';

    this.result = {
      id: this.id,
      description: this.description,
    };
  }

  SomeObject.prototype.doSomething = function(actual) {
    return 'do something';
  };

  SomeObject.prototype.calculate = function() {
    return 42;
  };

  return SomeObject;
};
var SomeObject = getLibrary().SomeObject();
var myInstance = new SomeObject({id: "myid"});
document.body.innerHTML = myInstance instanceof SomeObject;

If you ever want to find out which function most likely created myInstance, assuming nothing has modified the

SomeObject.prototype</code), you can access it through <code>myInstance.constructor
. In ES2015 and later versions, you can also retrieve the name of that function using its name property. Most modern browsers support this feature, even though it was only recently standardized. Therefore, on compliant browsers, you can easily get the function name like this:

console.log(myInstance.constructor.name); // "SomeObject"

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

Executing a post request using axios

Having some trouble with a post request using axios and it's refusing to cooperate. Here is the specific request I need to make. This is what I attempted: await axios.post( 'https://api.searchads.apple.com/api/v4/campaigns/XXXX/adgroups/targ ...

Using preventDefault on an anchor tag with the tel: protocol is ineffective

When a user clicks on a telephone number it should do nothing on desktop and on mobile it should call the number. Finding a solution seemed straightforward by using return false or preventDefault on desktop, but that approach has not proven effective so fa ...

Guide on exporting data from ejs files to a pdf file using pdfkit in a node js environment

Below is the code from my result.ejs file: <div style="width: 50%; margin: auto;"> <table class="table"> <thead> <tr> <th>SUBJECT</ ...

Invoke JavaScript when the close button 'X' on the JQuery popup is clicked

I am implementing a Jquery pop up in my code: <script type="text/javascript"> function showAccessDialog() { var modal_dialog = $("#modal_dialog"); modal_dialog.dialog ( { title: "Access Lev ...

Using a JSON file as a database for a project featuring HTML, CSS, and Vanilla JavaScript

Our task was to create a project that exclusively utilized JSON files for data storage. The data structure we were working with resembles the following: [ { "aircraftName": "Boeing 747", "departDate": 1640173020000, ...

Trouble with JavaScript preventing the opening of a new webpage

I need help with a JavaScript function to navigate to a different page once the submit button is clicked. I have tried using the location.href method in my code, but it's not working as expected. Even though I am getting the alert messages, the page i ...

Utilizing an Angular Service within a method, embedded in a class, nested inside a module

module Helper { export class ListController { static handleBatchDelete(data) { // Implementing $http functionality within Angular ... $http.post(data) } } } // Trigger on button click Helper.ListController. ...

How to optimize the utilization of Javascript variables within a Jquery function?

Currently, I am working on implementing an HTML5 min and max date range function. Initially, I wrote the code using variables and then embedded them in the correct attribute locations. However, after reviewing my code, my client (code reviewer) suggested ...

Navigating through information using Axios in React JS

Issue Currently, I am facing a challenge while trying to iterate through the data retrieved from an API call using Axios in a React.js application. The response is successfully received, but I am encountering difficulties when trying to display the inform ...

When clicked, the menu disappears successfully with the "show" functionality, but unfortunately, the "hide" feature is not working as intended

Within my menu, I have a section for portfolios that transforms into a dropdown on desktop hover and mobile click. The issue arises on mobile devices where the first click displays the menu correctly, but subsequent clicks do not trigger any change. I att ...

Implementing an onclick function to initiate a MySQL update query

<?php include_once("db.php"); $result=mysql_query("SELECT * FROM stu WHERE receiver='DM4'"); while($row=mysql_fetch_array($result)){ echo "<tr>"; echo "<td>" . $row['ptype'] . "</td>"; echo "<td>" . $row[&apo ...

Updating an HTML element by using the input value in a text field with JavaScript/jQuery

Although it may seem straightforward, I am new to Javascript and struggling to find or create the script I need. I have a list of BIN numbers for credit cards and want to extract the first 6 digits of the card number field to determine the type of card, an ...

JavaScript syntax issue detected, semicolon missing

I've encountered an issue with a form that contains potential errors defined in PHP. To dynamically change the form action based on the presence of errors, I have incorporated JavaScript into the process. The PHP error variable, $errors, has been conv ...

Using jsdom as a package in a Meteor application is not possible

Recently, I came across an issue with my packages.json file. It looks like this: { "jsdom" : "0.8.0", "request" : "2.25.0" } As part of my project, I have the following code snippet: if (Meteor.isServer) { Meteor.startup(function () { var _ ...

Is there a way to prevent the React history.push from reloading the component every time? I only want

After loading a component and redirecting using history.push, my component renders twice, triggering the componentDidMount() function twice as well. Below is a simplified version of my component. Everything runs fine with componentDidMount() running only ...

Using JQuery to create interactive dropdown menus with dynamic options

I am exploring the possibility of dynamically updating the choices available in an HTML dropdown menu based on the selection made by a user - consider this sample JSON data: series: [ {name: 'Company X', product: 'X1'}, {name: 'Co ...

The art of positioning images and creatively cropping

Seeking advice on allowing users to dynamically position and clip an image on a webpage. I've tried using CSS and JavaScript for clipping and resizing, but it's not working as expected. If PHP could provide a solution, that would be ideal for my ...

How can I position text below a ticked checkbox?

Having an issue with my HTML and jQuery code. Everything is working fine, but when I click on a checkbox, the text "FINISHED" appears below all checkboxes instead of just the one I clicked on. This is my html code: $('.label__checkbox').cli ...

Node.js HTTP request not returning any content in the body/message

Having some trouble with the requestjs package as I attempt to post data and receive a response. No matter what I do, the body response always ends up being undefined. const request = require('request'); request({ method: "POST", ...

Navigating through Next.Js using client side redirects

I am working on creating a redirect based on whether the user has a token saved in cookies or not. Take a look at my code snippet below: const Secret = () => { const router = useRouter(); const [token] = useState({ token: cookies.get("token ...