Facebook Pixel
this in Constructors and the new Keyword in JavaScript

What happens if you forget new with a function constructor?

The answer

this becomes the global object (or undefined in strict mode). Properties get added to window instead of a new object. The function returns undefined. This is a common bug with function constructors.

More FAQs in this in Constructors and the new Keyword in JavaScript

It creates a new empty object, sets this to that object inside the function, runs the function body, and returns this (the new object) unless the function returns its own object.

Yes. Calling a class constructor without new throws TypeError: Class constructor X cannot be invoked without 'new'. This prevents the forgotten-new bug that function constructors have.

Yes. If you call a bound function with new, this is a new object, not the bound this. However, any preset arguments from bind still apply to the new object.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Your learning library

Small steps. Big possibilities.

Find your next course. Build something great.

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.