Creating a typed JavaScript object using an object initializer - step by step guide

When creating an object using direct initialization and showing it in the console, the engine fails to assign it any type. This is not surprising, as the console considers displaying Object to be of little value. However, when a constructor function is used, the type is indeed assigned:

let obj1 = { d1: true, m1: function() { return 'MSG' } };
console.log(obj1);

let obj2 = new function SomeFunc() { };
obj2.anyField = 50;
console.log(obj2);

https://i.sstatic.net/KEARf.png

Is there an easy way to assign a type to an object directly during initialization without needing to define a function? Perhaps something akin to

__proto__: { constructor: { name: 'abcd' } }
exists that can achieve this effect? Ideally, a simpler solution would be preferred.

Answer №1

For an object to have a type, it must be associated with a constructor function. Consequently, in the context of your query (

excluding the creation of a new function
), the sole method of attributing a type to an object is by assigning it a pre-existing constructor function.

Answer №2

Create a named function and assign it to the obj1.__proto__.constructor.

It seems like this cannot be achieved within the object literal since the __proto__ properties need to be combined with the regular prototype.

let obj1 = { x: 42, y: "hello", z: []};
obj1.__proto__.constructor = function NewFunction() {};
console.log(obj1);

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

What is the syntax for accessing a nested object within the .find method?

Currently building an application in node.js. I am struggling with referencing the "email" element in the "userData" object within the Order model when using the find method. Any suggestions on how to properly refer to it? Order model: const orderSchema = ...

What is the reason for parsing JavaScript code when the page is first loaded?

I recently placed an Adsense (for content) code on my website in order to show a single ad: <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"> </script> <ins class="adsbygoogle" style="display:inline-block;width ...

How can I retrieve the current active filters when using the DataGrid component from @material-ui/lab?

I'm currently working on integrating material-ui's data grid into one of my pages. The main objective is to capture the state of filters and sorts for all columns, and save them as a link at the top of the page. This way, users won't have to ...

What is the best way to retrieve and subsequently transmit the unique identifiers from various tags?

I am in the process of building a website similar to a forum, where I retrieve and display posts from a database using PHP. In my HTML code, each post has a unique data-id value assigned by PHP. When clicking on the post, it triggers an event via Ajax to r ...

Pressing the reset button will initiate once the loader has finished

Hello everyone, I'm currently working on creating a button that transforms into a loader when submitted and then reverts back to a button after the form is successfully submitted. I suspect the issue lies within my JavaScript. I'm not sure how ...

A regular expression in JavaScript for matching unpredictable numbers without any specific words preceding them

For instance, I am looking to extract the numbers that do not have 'the', 'abc', or 'he' before them; the89 (no match) thisis90 (match 90) iknow89999 (match 89999) getthe984754 (no match) abc58934(no match ...

Utilize Node.js to seamlessly upload and display a .ppt or .pdf file on the Collaborate whiteboard feature

Does anyone know the proper API to use with node js in order to upload and view a .ppt or .pdf file in collaborate whiteboard? ...

Angular's onreadystatechange event is triggered when the state

Hey there, I'm new to Angular and had a question. Is it possible to use the $http service in Angular to trigger a function whenever there is any change in the ready state/status, not just for success or failure? If so, what would be the equivalent ang ...

What methods can I use to implement phone number validation in Ionic 2?

Looking to implement phone number validation in ionic 2, I came across an example on intlpnIonic which was designed for ionic 1. However, I want to achieve something similar to the image provided here: https://i.sstatic.net/qqSak.png My Query : How can I ...

Callback error in Ajax request

$(this).find(':submit').attr('disabled',true); $.ajax( { url:'/enviarSugerenciaMessageBoard', cache: false, type: 'POST', data: $(this).serialize(), ...

Executing a simulated onClick event in jQuery

Attempting to create a simulated onclick event on a drop-down menu has proved challenging for me. An IE object is being used to navigate to a page, where I need to modify a dropdown menu that contains an onchange event: $('select[name="blah"]') ...

Attempting to hash the password led to encountering an error

An issue was encountered: both data and salt arguments are required. This error occurred at line 137 in the bcrypt.js file within the node_modules directory. The code snippet below highlights where the problem is present: const router = require("express" ...

Encountering an issue with the for loop in React Native when using FlatList

As a beginner in programming, I am eager to dynamically render a list. The Navbar parent component holds the state with different Food Types categories such as Mexican and Chinese, each with its corresponding menu. My goal is to display each Food Type fol ...

Incorporating jQuery tooltips within a dynamically refreshing jQuery div

Having trouble with jQuery tooltips (using Tipsy) on a dynamically included page. The tooltips work well on regular pages, but when I include the page through PHP and set up auto-refresh using jQuery, the tooltips stop working properly. The issue seems to ...

Is there a way to implement tooltips on an element that has text-ellipsis enabled?

I am facing an issue with displaying an account number that exceeds 100 characters. I need to restrict the display with overflow hidden while still being able to show the full account number using a tooltip. Below is the code snippet: <span class="tex ...

Ensure that the context is used to effectively clear any existing data from the previous bar chart

I recently came across a cool codepen demo on this link. Upon clicking the first button followed by the second, the data transitions smoothly. However, there seems to be an issue where when hovering randomly over the bar charts at this source, the value ...

When invoking a function, jQuery may return an empty value

I am currently tweaking my jQuery script to retrieve a specific value upon page refresh in order to capture the return value. Initially, I attempted the following: var email_number = ''; // check if page refreshed or reloaded if (performance.n ...

Troubleshooting problems with Chart.js scaling upon page load

Using chart.js to display a horizontal bar graph. Interestingly, upon the initial loading of the website, only a fraction of one bar is visible, and the graph fails to properly adjust to the display size until the window is manually resized. This issue per ...

leveraging UI-Router for navigating based on app state and data

Is there a way to dynamically adjust Angular's ui-routing based on certain data conditions? For instance, let's say we need to create a subscription process where the user is informed of whether their subscription was successful or not. As the f ...

Transferring Variables to the Following Page Without Using a Form or Changing the URL

I have a question about passing a variable along with a link to exampleA.php without using URL extensions or form submitting. I've done some research and found that most people suggest using Ajax, but I want to handle the variable once I'm on the ...