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.
Syntax
var f = new foo(a);
is similar to the object creation to prototype.
var f = Object.create(foo.prototype);
foo.call(f, a);
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 en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
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);
Management
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);
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().