The return value problem of constructors in JavaScript and the process of the new object

Source: Internet
Author: User

The first thing to be clear is that the constructor in JavaScript does not need to have a return value, which is similar to Java. It can be considered that the most significant difference between a constructor and a normal function is that there is no return statement in the constructor, the normal function can have a return statement, the constructor uses the This keyword to define member variables and member methods, and normal functions do not use the This keyword to define member variables and methods.

function Person (name,sex) {      this.name = Name;this.sex = Sex;//return 1;//return true;//return "Aty"; return {" ReturnValue ": 11};} The new keyword is considered to be the creation object var aobj = new Person ("one", 1); alert (aobj.returnvalue);//11alert (aobj.name);//undefined


The constructor does not need to display the return value. When you use new to create an object (called a constructor), if the return is a non-object (number, String, Boolean type, and so on), the value is momentarily returned, and if the return is an object, the object is returned.

The following is a brief introduction to the process of the new object in javascript: var myObj = Newperson ("Aty");

1. Create an empty object . var obj = new Object ();

2. in the constructor person, point to the obj object that you just created

3. __proto__ of the created obj points to the prototypeof the constructor person. This step is to establish a direct correspondence between the object and the prototype. Firefox down through

The __proto__ property of the object can be accessed to the prototype, and IE does not expose the corresponding property.

4. execute the code in the constructor person ()

The return value problem of constructors in JavaScript and the process of the new object

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.