[JavaScript] Differences Between Regular and Constructor Functions

Tech Sharing 2019-03-07
[JavaScript] Differences Between Regular and Constructor Functions

A constructor is also a regular function, but conventionally capitalized and called with new. Code examples contrast object creation, instanceof, and call-based borrowing.

A constructor is also a regular function, created the same way, but conventionally capitalized.

function objectone(text){  // regular function
  var test = new Object();
  test.t = 300;
  test.run = function(){
    return (this.t - text);
  }
  return test;
}

var Object1 = objectone(1); // regular: call directly
function Objecttwo(text){  // constructor; this acts like an auto new Object
  this.t = 300;
  this.run = function(){
    return (this.t - text);
  }
  // no return needed
}

var Object2 = new Objecttwo("1"); // constructors must be called with new
// alert(Object1.run()); //299
// alert(Object2.run()); //299
// alert(Object1 instanceof objectone);  false // cannot identify the object
// alert(Object2 instanceof Objecttwo);  true  // identifies the reference from Objecttwo
// alert(Objecttwo("1")); // undefined; cannot call as a regular function

var Object3 = new Object();
Objecttwo.call(Object3, 2);  // constructor borrowing
// alert(Object3.run()); //298