0

I've came a cross an interesting situation in java script that I just can't wrap my head around :

Consider the following function :

T = function(){
this.help = 'foo';

var n = function(){};
return 'test';
}

When writing t = new T(); , t is an instance object and the return parameter is ignored.

however, when writing

T = function(){
this.help = 'foo';

var n = function(){};
return n;
}

writing t = new T(); will result in t being a function, and not an object. so the return value is NOT ignored and the this section is ignored instead(assigning local variables)

So my two questions :

  1. Why?
  2. Are there any other occasions where this happens?
Amit
  • 45,440
  • 9
  • 78
  • 110
Patrick
  • 3,289
  • 2
  • 18
  • 31

2 Answers2

3

When you return an object from a "construction function" (any function you invoke with new), that object becomes the return value. Any other return value is ignored and the newly constructed object is returned.

A literal string is not an object, but a function is.

Amit
  • 45,440
  • 9
  • 78
  • 110
1

From Mozilla JavaScript Reference:

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.)

In simpler words, this is how constructor calling works in JavaScript, i.e. if you return nothing or a primitive type (like plain string or numbers) or this, then they will be ignored and this will eventually be returned. However if you return an object or function from the constructor, that object will be returned with new.

I borrowed the following code from this blog post, which may be helpful here.

// Undefined return value.
function A() {
    return;
  }
  // Reference to instance.

function B() {
    return (this);
  }
  // String return value.

function C() {
    return ("string");
  }
  // Number retun value.

function D() {
    return (123);
  }
  // New object return value.

function E() {
    return ({
      foo: "bar"
    });
  }
  // New array return value.

function F() {
    return (["foo", "bar"]);
  }
  // New instantiation return value.

function G() {
    return (new A());
  }
  // Native "object" return value -- this one would be the same
  // for Number, Boolean, and String.

function H() {
    return (new Number(123));
  }
  // -------------------------------------------------- //
  // -------------------------------------------------- //
  // See what reference we have as a result of instantiation.

console.log(new A());
console.log(new B());
console.log(new C());
console.log(new D());
console.log(new E());
console.log(new F());
console.log(new G());
console.log(new H());

this returns

A {}
B {}
C {}
D {}
Object { foo="bar"}
["foo", "bar"]
A {}
Number {}
Ammar Hasan
  • 2,436
  • 16
  • 22