0

Many sources like MDN and this tutorial define a concept called "constructor" that should be used with the new keyword to create an instance in traditional OOP's sense. But what "constructor" means is not formally stated.

It seems to me that literally any function can be used with new. (Though function without any manipulation to this in its definition is not particularly useful when newed, because it merely returns an empty object). Is this correct?

wlnirvana
  • 1,811
  • 20
  • 36
  • 2
    yes, we can apply a new on a function, and it is not always empty, it can have variables, it can also be a closure, in JS everything is object, even the functions – Mister Jojo Apr 16 '21 at 02:07
  • No, there are some functions that will throw when you try to use `new` on them. – Bergi Apr 16 '21 at 02:15
  • yes, not any functions – Mister Jojo Apr 16 '21 at 02:22
  • @Bergi could you give some examples of functions that can not be `new`ed? – wlnirvana Apr 16 '21 at 02:25
  • 1
    Have a look at the answers to [How to check if a Javascript function is a constructor](https://stackoverflow.com/q/40922531/1048572), [Are there any JS objects for which IsCallable is false but IsConstructor is true?](https://stackoverflow.com/q/50109554/1048572) and maybe [JavaScript: Are all Standard Built-In Objects actually constructor functions?](https://stackoverflow.com/q/49431846/1048572) for the technical details – Bergi Apr 16 '21 at 02:25
  • 1
    @wlnirvana Arrow functions, class methods, many builtins, and of course `function Example() { if (new.target) throw new TypeError("Don't new() me!"); }` :-) – Bergi Apr 16 '21 at 02:26

1 Answers1

-1

When you use the new keyword, it creates a new object. When you create an instance of a class with new, it creates an object, and any properties in the constructor method will be initialized in the object as well.

narojo
  • 77
  • 5