Languages
[Edit]
EN

JavaScript - interesting trick, it is possible to create both class and function in one definition

14 points
Created by:
Root-ssh
178290

In this article, we're going to have a look at how to create class that allows user to create object with or without new operator in JavaScript.

Problem overview:

Simple problem solutions are presented below:

 

1. Optional new operator for class object with strict mode example

Edit

In this case recept how to make new object for same class definition with and without new keyword with strict mode is described.

Note: these approach work for web broser and NodeJS JavaScript with strict mode.

1.1. this or new object example

Edit

When this is not defined new object is cteated and assigned to self variable - it means ClassFunction was called as function.

1.2. Using instanceof operator example

Edit

Below example shows how to detect if new keyword were used to create ClassFunction.

 

2. Optional new operator for class object without strict mode example

Edit

In this case recept how to make new object for same class definition with and without new keyword without strict mode is described.

2.1. Dedicated runtime environment example

Edit

Note: this approach requires to adjust source code for web browser or node js - look on comment - to solve this problem check example 2.

2.2. Web browser or NodeJS auto detecting

Edit

This universal approach is useful to write code for web browser and node js both.

 

Alternative titles

  1. How to make new operator optional for function/class in JavaScript?
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join