new
JavaScript's new
operator creates a new object
that inherits from the operand's prototype member, and then calls the operand,
binding the new object to this
. This gives the
operand (which had better be a constructor function) a chance to customize the new
object before it is returned to the requestor.
If you forget to use the new
operator, you
instead get an ordinary function call, and this
is bound to the global object instead of to a new object. That means that your
function will be clobbering global variables when it attempts to initialize the new
members. That is a very bad thing. There is no compile-time warning. There is no
runtime warning.
By convention, functions that are intended to be used with new
should be given names with initial capital
letters, and names with initial capital letters should be used only with constructor
functions that take the new
prefix. This
convention gives us a visual cue that can help spot expensive mistakes that the
language itself is keen to overlook.
An even better coping strategy is to not use new
at all.
Get JavaScript: The Good Parts now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.