2

Based on these specs at MDN about how the new operator works:

The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

I am lead to believe that the new operator only overrides the return value if one hasn't been provided. Yet it seems that it always does so and you can never override it.

For example

function test() { return 1; }
new test() // returns {} and not 1

Can someone give an example where this is not the case, such as they are referring to in the docs?

npiv
  • 1,837
  • 15
  • 24

2 Answers2

5

You can overwite the result only with a non primitive value.

With primitive

function test() { this.bar = '42'; return 1; }
console.log(new test()) // {}

With object, without primitive

function test() { this.bar = '42'; return { foo: 'bar' }; }
console.log(new test()) //  { foo: 'bar' }; 

With array, without primitive

function test() { this.bar = '42'; return [42]; }
console.log(new test()) // [42]; 
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

In addition @nina-scholz answer we can use a new primitive object and a function to get access to primitive value from the function invoked with new operator

With appropriate new primitive object

function test() {
  this.bar = '42';
  return new Number(1);
}
const num = new test()

console.log(num.valueOf()) // 1
console.log(num + 0) // 1

With function as a work around, without primitive

function test() {
  this.bar = '42';
  return () => { return 1 };
}

console.log(new test()()) // 1
Roman
  • 19,236
  • 15
  • 93
  • 97