Question

How does JavaScript's new operator work?

#javascript

Answer

Although JavaScript is a prototypal inheritance language, it offers an object-making syntax that is reminiscent of the class-based languages.

The new operator is used in the *constructor invocation pattern*.

If a function is invoked with the new prefix, then a new object will be created with a hidden link to the value of the function's prototype member, and this will be bound to that new object.

The new prefix also changes the behavior of the return statement: if the return value is not an object, then this (the new object) is returned instead.

Functions that are intended to be used with the new prefix are called *constructors*. By convention, they are kept in variables with a capitalized name.

// When called with `new`, it makes an object with a status property
var Quo = function (string) {
  this.status = string;
};

var myQuo = new Quo("confused");
// => { status: "confused" }

[^1]: Douglas Crockford's "JavaScript: The Good Parts", Functions > Invocation > The Constructor Invocation Pattern

Learn

Author

xavi

Reviews
Last
next

Students 1