Monday, 27 March, 2023 UTC


Summary

We can use new.target to detect if a Javascript function is called as a constructor.
For example, let's say we have the following situation:
function Cat() {}

//  normal function call
Cat()
// call as a constructor
const myCat = new Cat()
We can use the new.target Javascript meta property to differentiate between the two different function calls:
function Cat() {
    if (new.target) {
        console.log('Called as a constructor')
    }
    else {
        console.log('Called as normal function')
    }
} 
This is quite nice because we can restrict a Js function to be called only as a constructor:
function Cat() {
    if (!new.target) {
        throw new TypeError('Cat() function needs to be called as a constructor'); 
    }
}
And you can use new.target.name to retrieve the name of the constructor:
function Cat() {
    if (new.target) {
        console.log(new.target.name) // Cat
    }
} 
Something similar to what the name property of a Javascript function can do.
The overall support for new.target is great, being available in all browsers.
The post How to check if a Javascript function was called with the new operator appeared first on Js Craft.