An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
December 27, 2022 04:10 pm GMT
Original Link: https://dev.to/devsmitra/exploring-the-power-of-newtarget-in-javascript-2p66
Exploring the Power of new.target in JavaScript
In JavaScript, the new.target property is a meta-property that can be used to determine whether a function was called with the new keyword. It returns a reference to the constructor function that was invoked with the new keyword, or undefined if the function was not called with new.
function MyClass() { if (new.target) { console.log('MyClass was called with new'); } else { console.log('MyClass was not called with new'); }}new MyClass(); // MyClass was called with newMyClass(); // MyClass was not called with new
new.target can be useful for implementing custom constructor functions, where you want to ensure that the function is always called with new, or for creating abstract base classes that cannot be instantiated directly.
function MyClass() { if (!new.target) { throw new Error('MyClass must be called with new'); }}
If you enjoyed reading this short blog, you may also want to check out my javascript short playlist on YouTube.
Must Read If you haven't
3 steps to create custom state management library with React and Context API
How to cancel Javascript API request with AbortController
Getting started with SolidJs A Beginner's Guide
More content at Dev.to.
Catch me on YouTube, Github, Twitter, LinkedIn, Medium, Stackblitz, Hashnode, HackerNoon, and Blogspot.
Original Link: https://dev.to/devsmitra/exploring-the-power-of-newtarget-in-javascript-2p66
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To