The creation of JavaScript objects is based on the construction method + prototype mode

Source: Internet
Author: User

In order to solve the problem of the prototype, we need to create the object by combining construction methods and prototypes, define the properties in the constructor method, and define the method in the prototype . This effective aggregation of the advantages of both, is currently the most commonly used in a way.

functionPerson (name,age,friends) {//property is defined in the constructor     This. Name =name;  This. Age =Age ;  This. Friends =friends;} Person.prototype={Constructor:person,//method is defined in the prototypeSayfunction() {alert ( This. name+ "[" + This. friends+ "]"); }}//This is where the properties are stored in their own space.varP1 =NewPerson ("Leon", 23,["Ada", "Chris"]);p 1.name= "John";p 1.friends.push ("Mike");//added a friend to P1.P1.say ();//John ["Ada", "Chris", "Mike"]varP2 =NewPerson ("Ada", 33,["Leon"]);p 2.say ();//Ada Leon

The memory model diagram looks like this:

The creation of JavaScript objects is based on the construction method + prototype mode

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.