Javascript - Constructor

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard > Javascript - Object

1 - About

Object - Constructor in Javascript of an object

Invoking a function with the new operator treats it as a constructor.

Unlike function calls and method calls, a constructor call passes a brand-new object as the value of this, and implicitly returns the new object as its result. The constructor function’s primary role is to initialize the object.

The constructor can be see as property of a function (object).

Not to confound with a function constructor.

Advertising

3 - Syntax

var f = new foo(a);

is similar to the object creation to prototype.

var f = Object.create(foo.prototype);
foo.call(f, a);

See Javascript - Call method

3.1 - Array as Argument

When calling a constructor with new, it's not possible to directly use an array and apply (apply does a Call and not a Construct). However, an array can be easily used with new thanks to spread syntax:

var dateFields = [1970, 0, 1];  // 1 Jan 1970
var d = new Date(...dateFields);

See Reference/Operators/Spread_operator

4 - Example

function myObject(arg){
   this.prop1 = arg;
   this.prop2 = arg + arg;
   this.prop3 = arg.toUpperCase;
}
 
var obj1 = new myObject("foo");
console.log("An object obj1 was created with the following structure:");
console.log(obj1);

5 - Management

5.1 - See the code of the constructor of an object

function myObject(arg){
   this.prop1 = arg;
   this.prop2 = arg + arg;
}
 
var obj1 = new myObject("foo");
console.log("The code of the constructor function of this object is:");
console.log(obj1.__proto__.constructor);

Advertising

5.2 - Get the objects of a constructor

Call queryObjects(Constructor) from the Console to return an array of objects that were created with the specified constructor.

For example:

  • queryObjects(Promise). Returns all Promises.
  • queryObjects(HTMLElement). Returns all HTML elements.
  • queryObjects(foo), where foo is a function name. Returns all objects that were instantiated via new foo().