Constructor Function

This is a special method used for creating and initializing the object.
Also known as Object Constructor Function.
In ES 2009 classes had to be defined using functions.
This function (known as a constructor function) will create a new class called MyClass.

function MyClass() { 
}

While most object orientated languages use a class-based inheritance model, JavaScript doesn't.
JavaScript classes are based on a prototype inheritance model.
This means that all JavaScript objects have a property called "prototype" which points to its corresponding "object prototype" object.
It is this "object prototype" that inherits the properties and methods.


You can create objects of this type by calling the constructor function with the new keyword.
Putting "new" in front of a function call turns that function into a constructor call.
This means it does 4 additional things:
*) a brand new empty object is created
*) the object is linked to something ( see later )
*) the function gets bound as the "this" keyword for the purposes of the function call
*) if the function does not return anything, then it will implicitly return "this"

var myObject1 = new MyClass(); 
var myObject2 = new MyClass();

A constructor can use the "super" keyword to call the constructor of the super class.
You always need to call "super" when defining the constructor of a subclass
All React component classes that have a constructor should start it with a super(props) call.



Using a Prototype is add properties and methods

You can define methods on this object using this prototype

MyClass.prototype.Method1 = function() { 
   console.log("this is a class method");
}

myObject1.Method1(); // this is a class method


Returns 'this' if the function does not return its own object.


You can also create a constructor function with parameters

function Person ( first, last ) { 
   this.firstName = first;
   this.lastName = last;
}
var myDad = new Person ("David", "Smith");


new Function (arg1, arg2, [ ... ], bodyString)

var myDad = { 
   init : function (first, last) {
      this.firstName = first;
      this.lastName = last;
}
Object.create(myDad);


this Keyword

When this keyword is used in a constructor function, this refers to the object when the object is created
When an object accesses the properties, it can directly access the property as person1.name

// constructor function 
function Person () {
    this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
console.log(person1.name); // John




© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext