The process by which JavaScript creates objects with new

Source: Internet
Author: User

Creating a custom object in JavaScript requires the new operator, so what is the process of creating an object?

For example, you now have the following constructor:

function person (name) {    this.name = name;} Person.prototype = {    Constructor:person,    sayname:function () {         alert (this.name);}; var jack = new Person ("Jack");

First, you must ensure that the new operator is followed by an object with a [[Construct]] internal method, or an exception will be thrown.

The next step is the process of creating the object:

1. First create a native object, assumed to be obj = {} or obj = new object.

2. Obtain the Prototype object of the constructor person and assign it to the [[Prototype]] property of obj. In Firefox it shows __pro__.

The internal method of the 3.call constructor, which assigns the this value to the newly created object, obj, and passes in the required parameters.

4. Execute the constructor and return the created object.

Here's one thing to note: Normally the constructor does not write the return statement, because it returns the newly created object by default. However, if you write the return statement in the constructor, if the return is an object, the function overwrites the newly created object and returns the object, and if the return is a primitive type such as a string, a number, a Boolean, and so on, the function ignores the return statement. Or return the newly created object.

The process by which JavaScript creates objects with new

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.