The study of new constructor in JS

Source: Internet
Author: User

Explanation of the new operator in JavaScript advanced programming:

New operator causes the constructor to change as follows:

  1. Create a new object;

  2. Assign the scope of the constructor to the new object (so this one points to the new object);

  3. Execute the code in the constructor (add attributes for this new object);

  4. returning new objects

/*Constr: Constructor args: Initialize parameters*/functionnewoperator (constr, args) {varThisvalue = Object.create (Constr.prototype);//Create a new object with the constructor's prototype object    varresult = Constr.apply (Thisvalue, args);//point the constructor to the new object and add a new property to the new function    if(typeofresult = = = ' object ' && result!==NULL) {        returnResult//return new Object    }    returnThisvalue;}

Look at the results of this piece of code

var a=5; function Test () {    a=0;    alert (a);    Alert (this. a);     var A;    alert (a);} Test (); New test (); 0500undefined0

And look at the results of this code.

var a=5; function Test () {    this.a=0;    alert (a);    Alert (this. a);     var A;    alert (a);} Test (); New test (); undefined0undefinedundefined0undefined

This code can be interpreted as defining var A; Then a is the local variable of the function, which can only be found within his active object, and when the test () is executed, THIS.A is equivalent to WINDOW.A, and when the new test () is executed, THIS.A This is equivalent to the property of the new object, and a is a local variable of the test function, which is okay with the new object

The study of new constructor in JS

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.