JS 7 Ways to create objects (i)

Source: Internet
Author: User
Tags uppercase letter

1. Factory mode (Factory)

1 functionCreateperson (name, age, title) {2     varo =NewObject ();3O.name =name;4O,age =Age ;5O.title =title;6O.sayname =function(){7Alert This. Name);8     }9     returno;Ten }    One  A varPerson1 = Createperson ("Greg", "Doctor"); - varPerson2 = Createperson ("Lisa", "Teacher");

Factory mode does not recognize the type of object.

2. Constructor mode (Constructor)

1 functionPerson (name, age, job) {2      This. Name =name;3      This. Age =Age ;4      This. Job =job;5      This. Sayname =function(){6Alert This. Name);7     }8 }9 varPerson1 =NewPerson ("Nicholas", "Software Engineer");Ten varPerson2 =NewPerson ("Greg", "Doctor");

By convention, constructors should always start with an uppercase letter.

To create a new instance of a person, you must use the new operator.

Person1 and Person2 each hold a different instance of person, both of which have a constructor attribute that points to person:

Alert (Person1.constructor = = person)  //truealert (person2.constructor = = person)  //  True

Constructor problem: All methods in the constructor are recreated on each instance.

Alert (Person1.sayname = = person2.sayname);    // false

JS 7 Ways to create objects (i)

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.