The new operator creates an instance of a user-defined object type or a built-in object that has a constructor function. Its behavior depends on the return value of the constructor:
- Standard Behavior: The resulting instance has access to properties defined within the constructor and methods defined on the constructor's prototype.
- Object Return: If the constructor explicitly returns an object, the
new operator returns that object instead of the newly created instance. - Primitive Return: If the constructor returns a primitive value (e.g., a string or number), the return value is ignored, and the
new operator returns the newly created instance.
// Case 1: Standard
function Factory(name) { this.name = name; }
Factory.prototype.sayHi = function() { console.log('Hi'); };
var foo = new Factory('Jack'); // foo.name is 'Jack', foo.sayHi() works
// Case 2: Returns Object
function Factory(name) {
this.name = name;
return { job: 'developer' };
}
var foo = new Factory('Jack'); // foo.job is 'developer', foo.name is undefined
// Case 3: Returns Primitive
function Factory(name) {
this.name = name;
return 'hello';
}
var foo = new Factory('Jack'); // foo.name is 'Jack' (primitive return ignored)