Understand the different patterns of JavaScript creation objects

Source: Internet
Author: User
Tags object object

PS: Front-end slag for the first time to write a blog, typesetting what is not clear, the follow-up will slowly improve.


After a lapse of two months to review the front end, found a lot of things have forgotten, yesterday just saw constructor and prototype a face, go back to check information and read books, to the object of understanding than before the time more in-depth. This article only provides an auxiliary understanding of the various patterns that JavaScript creates for objects, and where there are errors, please correct them.



Creating objects

Literal object

var person = {name: ' MyName ', Age: "", "sayname:function () {alert (this.name)}}

Cons: Every time you create an object you need to write a piece of code, and the different places only have a few data, the code is not reused.


Factory mode

<span style= "White-space:pre" ></span>function person (name,age) {<span style= "White-space:pre" > </span>var o = new Object (); <span style= "white-space:pre" ></span>o.name = Name;<span style= " White-space:pre "></span>o.age = Age;<span style=" white-space:pre "></span>o.sayname = function ( {<span style= "White-space:pre" ></span>alert (this.name); <span style= "White-space:pre" ></ Span>}<span style= "White-space:pre" ></span>return o;<span style= "White-space:pre" ></span } <span style= "White-space:pre" ></span>var p1 = person ("MyName", 21);
<pre name= "Code" class= "JavaScript" > <span style= "White-space:pre" ></span>alert (P1 instanceof Object); <span></span>//true
<span style= "White-space:pre" ></span>alert (p1 instanceof person); <span></span>//false

This solves the problem of code not being reused, but the book points to a new drawback: there is no problem solving object recognition.

What is the meaning of this sentence, before reading the time did not carefully distinguish between their differences. Checked the information: the newly created object through the Factory mode has no way of knowing what type this object is. We create objects with the person as a class, but in the end, the object's class is not a person, but an object.

Look at the code: The person is just a normal function and is also called normally. An Object object is created in the person function and assigned to properties and methods to return it. The object is all that is done, so the objects we create naturally have nothing to do with the person, and the person is just a function that is executed.




Constructor mode

<span style= "White-space:pre" ></span>function person (name,age) {<span style= "White-space:pre" > </span>this.name = Name;<span style= "white-space:pre" ></span>this.age = Age;<span style= " White-space:pre "></span>this.sayname = function () {<span style=" White-space:pre "></span>alert (this.name); <span style= "White-space:pre" ></span>}<span style= "White-space:pre" ></SPAN>} <span style= "White-space:pre" ></span>var p1 =new person ("MyName", 21); <span style= "White-space:pre" ></span>alert (P1 instanceof Object); <span style= "White-space:pre" > </span>//true<pre name= "Code" class= "JavaScript" > <span></span>alert (p1 instanceof person); <span style= "White-space:pre" ></span>//true

At this point, you can find the object that you created through the constructor pattern to successfully identify its type (person type).
Creating an object from this method actually passes a few steps:

1.new person (); //Create a Person object instead of object

2. Assigning the scope of a constructor to a new person object (this points to a new object)

3. Execute code in the person function (Assignment)

4. Returning new objects

We are new to the person object, and the person type inherits from the object type, so the P1 object in the code is both an object of type objects and an object of type person.

Looks like it's perfect? Hehe, the book raises a question: the main problem with constructors is that each method is recreated on each instance ( note the red font ).

what does that mean? Special research: In our constructor, there is sayname this method declaration , Declaring the sayname of this object is a method that is created at the same time as the object is created. I created two objects, created two sayname methods, created three objects and created three sayname methods. Look at the code:

<span style= "White-space:pre" ></span>function person (name,age) {<span style= "White-space:pre" > </span>this.name = Name;<span style= "white-space:pre" ></span>this.age = Age;<span style= " White-space:pre "></span>this.sayname = function () {<span style=" White-space:pre "></span>alert (this.name); <span style= "White-space:pre" ></span>}<span style= "White-space:pre" ></SPAN>} <span style= "White-space:pre" ></span>var p1 = new Person ("MyName"); <span style= "White-space:pre" ></span>var P2 = new Person ("myName2"), <span style= "White-space:pre" ></span>alert ( P1.sayname = = p2.sayname); <span style= "White-space:pre" ></span>//false
The code here illustrates that the same method for both objects is not the same object (pointing to a different memory address)


However, our Sayname method seems to look exactly the same: the function is to pop up the warning box and tell us what the object's name is.

Since this is a method, why create multiple times? That's superfluous.

This is the disadvantage of creating objects in the constructor pattern.



Prototype mode

Each type has a prototype (prototype) property that contains properties and methods that are shared by all instances of that type. That's what the book says, but it may be difficult for people who have just touched the prototype to understand it.

A different expression: each type of prototype is like a model, with properties and methods, as long as it is a new object from this type, and the properties and methods are the same as this prototype.

Take a look at the examples to understand better:

<pre name= "Code" class= "JavaScript" ><span style= "font-family:arial, Helvetica, Sans-serif;" ><span style= "White-space:pre" ></span></span>
<span style= "White-space:pre" ></span>function person () {};<span style= "White-space:pre" ></ Span>person.prototype.name = "MyName"; <span style= "White-space:pre" ></span>person.prototype.age = 18 ; <span style= "white-space:pre" ></span>person.prototype.sayname = function () {<span style= " White-space:pre "></span>alert (this.name); <span style=" White-space:pre "></span>}<span Style= "White-space:pre" ></span>var p1 = new Person (); <span style= "White-space:pre" ></span>var P2 = new Person (); <span style= "White-space:pre" ></span>alert (p1.sayname==p2.sayname);//true

At this point, P1 and P2 two objects, both property and method, point to the same place. The P1 property is the same thing as the P2 property (memory address is the same), similarly, p1 and P2 's same name method is also the same relationship. This means that I created two person objects, but the properties and methods of the objects I only instantiated once, no matter how many objects I create, are instantiated only once, instantiating the prototype object of person.

The properties and methods of the new object point to the property and method of the same name as the prototype object. When changing the properties and methods of the prototype, the properties and methods of the corresponding object will also be changed. That is, the properties and methods of an object are not the properties and methods of their own, but the properties and methods that point to the prototype. Let's look at an example:

function person () {}; Person.prototype.name = "MyName"; Person.prototype.age = 18; Person.prototype.sayName = function () {alert (this.name);} var p1 = new person (); alert (p1.age);//18person.prototype.age = 20;alert (p1.age);//20
The P1 object is 18 before the property of the prototype is changed, and the property of the prototype is changed to 20, which does not operate on the P1 object. This example illustrates that the properties and methods of the objects produced by the prototype pattern do not belong to themselves, but rather to the same name properties and methods of the prototype. If you want an object to have its own properties and methods, you can assign values to the object itself, and the new properties and methods will overwrite the same name properties and methods in the prototype.

Disadvantages of prototype mode: 1. All instances will get the same property value by default (this is only a minor issue) 2. The nature of sharing (the biggest problem)

The shared nature of the prototype pattern is a good thing for a function like Sayname, since the prototype schema is used to create only one function. But for other properties (non-functions) the problem is that there is nothing wrong with the properties of the primitive type, and the problem is the property of the reference type . See Example:

<span style= "White-space:pre" ></span>function person () {<span style= "White-space:pre" ></span ><span style= "White-space:pre" ></span>}<span style= "White-space:pre" ></span><span Style= "White-space:pre" ></span> person.prototype = {<span style= "White-space:pre" ></span> Constructor:person,<span style= "White-space:pre" ></span> Name: "MyName", <span style= "White-space: Pre "></span> age:29,<span style=" White-space:pre "></span> sayname:function () {<span style=" White-space:pre "></span> alert (this.name); <span style=" White-space:pre "></span>}, <span Style= "White-space:pre" ></span>friends:["a", "B"]<span style= "White-space:pre" ></span>}< Span style= "White-space:pre" ></span>var person1 = new Person (); <span style= "White-space:pre" ></ Span>var Person2 = new Person (); <span style= "White-space:pre" ></span>person1.friends.puSH ("C"); <span style= "White-space:pre" ></span>alert (person1.friends); <span style= "White-space:pre" ></span>//abc<span style= "White-space:pre" ></span>alert (person2.friends); <span style= " White-space:pre "></span>//abc<span style=" White-space:pre "></span>alert (person1.friends=== Person2.friends);//true
The Friends property is of type array,This modifies the value of the Friends property of the Person1, modifies the value of the reference type of the same address, and the value of the corresponding Person2-pointed prototype of the Friends is the value of the change. Prototype mode does not work if you do not want the friends value of the Person2 to be changed. Therefore, for properties of this reference type, you cannot use the prototype pattern to create an object.



Combination mode

In all the analysis of all the objects created, each of them has its drawbacks, so how do you best create an object?

Using combination mode: Constructor mode + prototype mode

Assign values to the object's non-shared properties, use the constructor pattern, assign values to the object's methods and shared properties, and use the prototype method to see the code:

<span style= "White-space:pre" ></span>function person (name,age) {<span style= "White-space:pre" > </span>this.name = Name;<span style= "white-space:pre" ></span>this.age = Age;<span style= " White-space:pre "></span>this.friends = [" A "," B "]<span style=" White-space:pre "></span>}// Constructor mode <span style= "White-space:pre" ></span>person.prototype = {<span style= "White-space:pre" > </span>constructor:person,<span style= "White-space:pre" ></span>sayname:function () {<span Style= "White-space:pre" ></span>alert (this.name) <span style= "White-space:pre" ></span>}< Span style= "White-space:pre" ></span>}//prototype mode <span style= "White-space:pre" ></span>var Person1 = New Person ("myName1"), <span style= "White-space:pre" ></span>var person2 = new Person ("myName2", 20); <span style= "White-space:pre" ></span>person1.friends.push ("C"); <span style= "White-space:pre" ></span>alert (person1.friends);//abc<span style= "White-space:pre" ></span>alert (person2.friends );//ab<span style= "White-space:pre" ></span>alert (person1.friends===person2.friends);//false<span Style= "White-space:pre" ></span>alert (person1.sayname===person2.sayname);//true
This model is one of the most widely used and most recognized methods of creating custom types.

Of course, in addition to the above several models, there are a variety of ways to create objects, according to the actual needs to choose the right way, I do not have a very deep study, not to be described here.

There is no special feeling about blogging before blogging, and I feel dispensable. But really in order to write a happy blog, it is not so casually, the understanding of technical knowledge must be in-depth understanding before they dare to write up, knowledge and through careful scrutiny to make it easy to write up. In a word, writing a blog can help you to understand the knowledge point very much. As a front-end technology newcomer, hope that they can improve their own strength through the blog, there is the wrong place, welcome to spray, open.



<span></span>alert (P1 instanceof Object);

Understand the different patterns of JavaScript creation 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.