Javascript does not support real classes like Java, C #, and other languages. However, pseudo classes can be defined in js. The tool to achieve this is the constructor and prototype object. First, we will introduce the constructors in js.
The syntax for creating objects in Javascript is followed by a function call after the new operator. For example
Copy codeThe Code is as follows:
Var obj = new Object ();
Var date = new Date ();
The new operator first creates a new object without any attributes, and then calls this function to pass the new object as the value of this keyword.
The implementation of var date = new Date () pseudo code is
Var obj = {};
Var date = Date. call (obj );
The role of the constructor is to initialize a newly created object and set its attributes before using the object. If you define your own constructor, you only need to compile a function that adds attributes for this. The following code defines a constructor:
Copy codeThe Code is as follows:
Function Rectangle (w, h)
{
This. width = w;
This. height = h;
}
Then, you can use the new operator to call this function to create an object instance.
Var rect = new Rectange (4, 8 );
Return Value of the constructor
Constructors in Javascript usually do not return values. However, a function allows a return value. If a constructor has a return value, the returned object becomes the value of the new expression. In this case, the object as this will be discarded.