2

I've done some tests and I'm wondering why a new TestOne() evaluates to a new instance of the function but a new TestThree() evaluates to the return value.

It appears that this depends on whether an object is returned or a primitive type. I'd expect new TestThree() to evaluate to TestThree {} (an instance of it). What happens to the instance of TestThree that's created by new?

What are the rules behind this and why?

function TestOne() {
    return 123;
}

new TestOne(); // TestOne {}
TestOne(); // 123

function TestTwo() {
}

new TestTwo(); // TestTwo {}
TestTwo(); // undefined

function TestThree() {
    return new TestOne();
}

new TestThree(); // TestOne {}
TestThree(); // TestOne {}
Lucien
  • 776
  • 3
  • 12
  • 40
  • 3
    Looks like if you return an object that is used. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new#Description "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." – Roland Starke Aug 10 '18 at 11:43
  • Ah, that answers my question- thank you. – Lucien Aug 10 '18 at 11:47

0 Answers0