Constructor for the creation of JavaScript objects

Source: Internet
Author: User

Created by constructors and similar to factory-based creation, the biggest difference is that the name of the function is the name of the class, and the first letter is capitalized according to the Java conventions.

When you create an object using a constructor, The definition of the property is done inside the function through the This keyword .

functionPerson (name, age) { This. Name =name;  This. Age =Age ; //the problem is that all objects will allocate space for the behavior     This. Say =function(){//Note: Say is also a property of personAlert This. Name + "--" + This. Age); }}//creating objects with new personvarP1 =NewPerson ("Leon", 22);varP2 =NewPerson ("Ada", 32);p 1.say (); P2.say (); Alert (typeofp1);//Object//you can use constructors to detect the type of an object in the following waysAlert (P1instanceofperson);//trueAlert (P1.say = = P2.say);//false because the method is defined in the class, all two say are not the same

The first problem with creating a constructor is that each object will have a copy of the method, and if the object has many methods, the space occupancy will be greatly increased .

How to improve? A function can be defined in a global variable so that the behavior/method in the class points to the same function.

functionPerson (name, age) { This. Name =name;  This. Age =Age ;  This. Say =say;}functionsay () {alert ( This. Name + "--" + This. age);}varP1 =NewPerson ("Leon", 22);varP2 =NewPerson ("Ada", 32);p 1.say (); P2.say (); Alert (P1instanceofperson);//trueAlert (P1.say = = P2.say);//true

Set the behavior to the global behavior, if all the methods are designed as global functions, this function can be called by the window , this time it destroys the encapsulation of the object,

And if an object has a large number of methods, it will result in a large number of global functions in the entire code, which will not be conducive to development.

Constructor for the creation of JavaScript objects

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.