A detailed description of JavaScript custom constructors-basic knowledge

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.