JavaScript does not support real classes in languages like Java, C #, and so on. However, in JS can be defined pseudo class. The tool to do this is the constructor and the prototype object. First, the constructor in JS is introduced.
The syntax for creating objects in JavaScript is the invocation of a function after the new operator. Such as
Copy Code code as follows:
var obj = new Object ();
var date = new Date ();
operator New first creates a new object that has no attributes, and then calls the function to pass the new object as the value of the This keyword.
The implementation of the pseudo code of the var date = new Date () is
var obj = {};
var date = Date.call (obj);
The function of a constructor is to initialize a newly created object and set the properties of the object before using the object. If you define your own constructor, you just need to write a function that adds a property to this. The following code defines a constructor:
Copy Code code as follows:
function Rectangle (W, h)
{
This.width = W;
This.height = h;
}
You can then call this function using the new operator to create an instance of the object
var rect = new Rectange (4,8);
The return value of the constructor
Constructors in JavaScript typically do not return a value. However, the function is allowed to have 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.