JavaScript: creating instances without the 'new' keyword

I'm looking for help understanding why the code snippet below is functional:

<script>
    var re = RegExp('\\ba\\b') ;
    alert(re.test('a')) ;
    alert(re.test('ab')) ;
</script>

Notably, there is no new operator in the first line of this code.

To my knowledge, a constructor in JavaScript is a function responsible for initializing objects created by the new operator without necessarily returning anything.

Answer №1

Typically, when something is identified as a constructor, it should be invoked using new. However, the RegExp function has a specific behavior known as "factory" for cases where it is called as a regular function instead. To learn more about this behavior, refer to Section 15.10.3 of the ECMAScript (JavaScript) specification:

15.10.3 The RegExp Constructor Called as a Function
15.10.3.1 RegExp(pattern, flags)
If the pattern is an object labeled R with [[Class]] property set to "RegExp" and flags are undefined, return R without any changes. If not, utilize the RegExp constructor by passing the pattern and flags arguments to it and return the object created by that constructor.

It is possible to define your own JavaScript constructor functions to allow omission of the new keyword by detecting if they have been called as functions and then correctly calling themselves. However, this can lead to confusing code and is not recommended. Additionally, this cannot be achieved using the modern class syntax; the older function syntax must be used instead.

Answer №2

+1 TJ Crowder understands it well. The ECMAScript standard specifically outlines the behaviors of built-in constructor functions when called as regular functions. There are times when the constructor simply calls itself back, but there are also instances that are more complex.

Constructors in JavaScript [...] should not be expected to return anything

Typically, a constructor can disregard this and instead return an independent object:

function Thing() {
    return {'foo': 1};
}

In such cases, you can treat the function both as a constructor (using new) or a regular function.

If a constructor does not return anything, which is common for constructors, the new operator automatically ensures that it returns the newly created object passed as this. In this scenario, you have to use new.

Relying on a constructor to function like a plain function is not recommended, and the alternative behaviors of built-in constructors are seldom useful. It's generally advised to stick with using new.

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

Ways to dynamically update a div with data from a JSON response

I'm currently in the process of developing a search platform. I have three static divs on the search results page that display certain content, all containing similar code. For example: <div id="result" class="card"> <img src="hello.png" ...

Is it possible to implement nested views with Angular's built-in ngRoute module (specifically angular-route.js v1.3.15)?

For a project I'm working on, we have decided not to use UI router and are only using ngRoute. I need to create nested views - is it possible to achieve this with just ngRoute without any additional library support? If so, could you please provide a w ...

Tips for accessing and modifying local JSON data in a Chrome Extension

I am working on an extension and need to access and modify a local JSON file within the extension's directory. How can I accomplish this task? ...

Implementation of Oriented Bounding Box (OBB) in THREE

After utilizing the Yuka_OBB implementation to create an oriented bounding box, I have some inquiries about the results achieved: Bed (AABB) https://i.sstatic.net/OgZBU.png Bed (OBB) https://i.sstatic.net/fzOOW.png Wall (AABB) https://i.sstatic.net/R ...

Material UI Appbar is throwing an error with an invalid hook call

For my project, I needed to create a simple app bar, so I decided to use the code provided on the Material UI website. Here is the component's code that I used: import React from 'react'; import { fade, makeStyles } from '@material-ui/c ...

Issue: The material attributes need to be structured as an object containing field names as keys, or a function that generates the object

I recently added a Materials collection to my app's MongoDB database schema, which already had Customers and Tickets. While everything was working fine before the addition, I encountered an error message that reads: Error: Material fields must be an ...

Determine the position of a nested object within a multidimensional array using JavaScript/TypeScript

My objective is to obtain the complete index of a complex object within a multidimensional array. For example, consider the following array: var arr = [ { name: "zero", children: null }, { name: "one", children: [ { ...

What causes the variance in AJAX errors between IE and Chrome browsers?

Consider the code example provided below: <script> function xyz() { $.ajax({ type: "GET", url: "https://zx/xyz/uvw", timeout: 6000, dataType: "jsonp", ...

How can you utilize functions from external files within Angularjs controllers that are not classified as controllers themselves?

I have a unique scenario that I need help with. In my project, I am using a javascript file with three.js to render some models. To combine my frontend WebGL rendering with a backend library, I used Browsefiy to create a single js file named script.js. ...

Javascript/Typescript Issue with Closures - Storing a function of an object as a variable

Struggling with understanding JavaScript/TypeScript closures even after reviewing multiple examples online. Here's the code causing me issues: let obj = { message: '222', printMessage: function() { return this.message }, } c ...

What are the steps to resolve a Fetch request issue with a Node.js server?

I am attempting to make a simple POST request using the fetch method. I am working on building a contact form using Vanilla Javascript, HTML, and CSS on the front end, while utilizing Node.js / Express on the backend. Take a look at my front end code: ...

Guide on parsing an Array of arrays using JSON.parse

I have received a JSON.stringified Array of arrays in a variable named request. alert(request); When I alert the above, I get the following message: "[[\"0\",\"MahaShivRatri\"],[\"0\",\ ...

Instructions for incorporating a glTF model into the environment:

I'm having trouble adding a 3D object to my scene. An error occurred: Uncaught TypeError: Class constructor ol cannot be invoked without 'new' at new GLTFLoader The main line causing the error is let loader = new THREE.GLTFLoader(); I&apo ...

What are some ways to prevent a submit event from occurring?

When my form is submitting, I am executing a function. $('#form-target').submit(function(){ makechange(); return false; }); However, there are situations where I need to prevent this event from happening. ...

What is the best way to apply a datepicker to all textboxes with a specific class using jQuery?

I have enclosed multiple fields within div elements in order to specify them with a datepicker for a better user experience. For example: <div class="need-date" > <label>Appointment Date</label> <input id="id_appointment_date" ty ...

BibInt output in JavaScript shows unusual data when combined with NaN

Could someone help me understand why NaN is considered a 'number'? console.log(typeof 1n+NaN); console.log(typeof NaN+1n); I couldn't find any mention of these types in the official documentation. ...

Guide to creating and importing a JSON file in Wordpress

I'm looking to save a list in a JSON file within the Wordpress functions.php file. Can you guide me on how to achieve this? function ScheduleDeletion(){ ?> <script type="text/javascript"> var day = (new Date).get ...

Asynchronous database calls within a loop that do not wait

I'm facing a challenge while trying to access a database during JSON parsing. This particular piece of code has become a nightmare for me: function loopColumns(val, cb){ db.one('select tag_name from t_tag where tag_id = $1', val) ...

display html once the component is finished rendering in Angular 2

After making an API call in my app component and receiving a response, I need to determine which div to display and which one to hide. However, the HTML is rendered before the component process is complete. Here is an example of the code: user.service.ts ...

What is the process for including an optional ngModelGroup in Angular forms?

I'm encountering an issue with incorporating the optional ngModelGroup in angular forms. Although I am familiar with how to use ngModelGroup in angular forms, I am struggling to figure out a way to make it optional. I have attempted to pass false, nu ...