JavaScript Object-oriented learning the problem of creating objects with six prototype patterns, combining the constructor pattern and prototype schema to create objects

Source: Internet
Author: User

First, careful analysis of the previous prototype mode to create the object method, found that the prototype schema creation object, there are some problems, as follows:

1, it omitted to pass the initialization parameter for the constructor function this link, the result all instances will obtain the same attribute value in the default situation, this is not the biggest problem!

2, the biggest problem is that all the attributes in the prototype are shared by many instances, which is appropriate for the function, and for those that contain the base value, because we know that you can add a property of the same name on the instance, you can hide the corresponding property in the prototype. However, for attributes that contain the value of the application type, the problem is very serious and the code is as follows:

functionPerson () {}person.prototype={constructor:person, Name:"Zhang San", Age:22, Job:"Coder", friends:["John Doe", "Harry"], Sayname:function() {alert ( This. Name); }}varperson1=NewPerson ();varPerson2=NewPerson ();p Erson1.friends.push ("Zhao Liu");  alert (person1.friends); //output: John Doe, Harry, Zhao Liualert (person2.friends);//output: John Doe, Harry, Zhao Liu

Analyzing the code above, when we add a friend for Person1, we find that Person2 has also been added a friend, but this is not what we want, and this is due to the shared nature of the prototype pattern, as long as any one instance modifies the property value in the Prototype Property object, All instances associated with the prototype object will be affected!

JavaScript Object-oriented learning the problem of creating objects with six prototype patterns, combining the constructor pattern and prototype schema to create objects

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.