Detailed description of JavaScript-based custom Constructor

Source: Internet
Author: User

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.

Related Article

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.