Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
The new.target in JavaScript
The new.target is a metaproperty that allows us to determine at runtime whether a function or constructor was called using the new keyword or not. It returns undefined when called as a regular function and references the constructor when called with new.
Basic Syntax
function MyConstructor() {
if (new.target) {
// Called with 'new'
} else {
// Called as regular function
}
}
Example: Detecting Constructor Usage
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>new.target Example</title>
</head>
<body>
<h2>new.target in JavaScript</h2>
<div id="result"></div>
<button onclick="testConstructor()">Test Constructor</button>
<script>
function Student(name, age) {
console.log("new.target:", new.target);
if (!new.target) {
document.getElementById('result').innerHTML =
"Error: Student should be used with the new operator";
return;
}
this.name = name;
this.age = age;
document.getElementById('result').innerHTML =
`Student created: ${this.name}, age ${this.age}`;
}
function testConstructor() {
// This will trigger the error
Student("John", 25);
// This would work correctly
// let student = new Student("John", 25);
}
</script>
</body>
</html>
Example: Proper Constructor Usage
function Person(name, age) {
console.log("new.target:", new.target);
if (!new.target) {
throw new Error("Person must be called with 'new'");
}
this.name = name;
this.age = age;
}
// Correct usage with 'new'
try {
let person1 = new Person("Alice", 30);
console.log("Created:", person1.name, person1.age);
} catch (error) {
console.log("Error:", error.message);
}
// Incorrect usage without 'new'
try {
let person2 = Person("Bob", 25);
} catch (error) {
console.log("Error:", error.message);
}
new.target: [Function: Person] Created: Alice 30 new.target: undefined Error: Person must be called with 'new'
Class Constructors
In ES6 classes, new.target helps detect inheritance patterns:
class Vehicle {
constructor(type) {
if (new.target === Vehicle) {
throw new Error("Vehicle is abstract - cannot instantiate directly");
}
this.type = type;
}
}
class Car extends Vehicle {
constructor(brand) {
super("car");
this.brand = brand;
}
}
// This will work
try {
let myCar = new Car("Toyota");
console.log("Created car:", myCar.brand, myCar.type);
} catch (error) {
console.log("Error:", error.message);
}
// This will throw an error
try {
let vehicle = new Vehicle("generic");
} catch (error) {
console.log("Error:", error.message);
}
Created car: Toyota car Error: Vehicle is abstract - cannot instantiate directly
Comparison Table
| Call Method | new.target Value | Usage |
|---|---|---|
new MyFunction() |
References constructor | Constructor call |
MyFunction() |
undefined |
Regular function call |
| Arrow functions | Inherits from enclosing scope | N/A |
Key Points
-
new.targetisundefinedwhen function is called normally - References the constructor when called with
new - Useful for enforcing constructor usage patterns
- Helps create abstract classes in ES6
Conclusion
new.target provides a reliable way to detect constructor usage and enforce proper instantiation patterns. It's particularly useful for creating abstract classes and ensuring functions are called correctly.
Advertisements
