Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ugultopu/d21b9606dd31eff2b6027abc78da0197 to your computer and use it in GitHub Desktop.
Save ugultopu/d21b9606dd31eff2b6027abc78da0197 to your computer and use it in GitHub Desktop.
Observing what we obtain when we call a function using the "new" operator, when the function explicitly returns a value

Code:

// Undefined return value.
function A() {
  this.name = 'Name';
  return;
}

// Reference to instance.
function B() {
  this.name = 'Name';
  return( this );
}

// String return value.
function C() {
  this.name = 'Name';
  return( "string" );
}

// Number return value.
function D() {
  this.name = 'Name';
  return( 123 );
}

// New object return value.
function E() {
  this.name = 'Name';
  return( { foo: "bar" } );
}

// New array return value.
function F() {
  this.name = 'Name';
  return( [ "foo", "bar" ] );
}

// New instantiation return value.
function G() {
  this.name = 'Name';
  return( new A() );
}

// Native "object" return value -- this one would be the same
// for Number, Boolean, and String.
function H() {
  this.name = 'Name';
  return( new Number( 123 ) );
}

function I() {
  this.name = 'Name';
  return function() {
    return 5;
  }
}


// -------------------------------------------------- //
// -------------------------------------------------- //


// 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() );
console.log( new I() );

Output:

A {name: "Name"}

B {name: "Name"}

C {name: "Name"}

D {name: "Name"}

{foo: "bar"}

(2) ["foo", "bar"]

A {name: "Name"}

Number {123}

ƒ () {
    return 5;
  }

Credits

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment