JavaScript Create object

Source: Internet
Author: User
Tags define object definition function definition functions instance method interface access


One, the object



ECMA-262 defines an object as an unordered collection of attributes that can contain basic values, objects, or functions. So the object in JS is a set of key-value pairs.



In object-oriented languages, you create any number of object instances with the same properties and methods through the class. But JS does not have the concept of class, then I first through an example to illustrate JS no "class" concept contains philosophy. This will make beginners very confused, but also because the "class" concept, JS objects have no other programming language vitality. In fact, the object of JS "class" is from scratch, and constantly evolve, eventually disappeared in the invisible.



For example: small tadpoles to find their mother's story, tadpoles in their own type of evolving process, gradually became the same as Mother's "class."



Code:


<! DOCTYPE html>


Effect:






(1) JS program began to produce a life object Life,life was born just a bare object of life, without any attributes and methods.



(2) The first life evolution, the living object has the Body property, and has a say method, looks like an "egg".



(3) The Second Life evolution, it has a "tail" and "gills", with the tail and gill properties, indicating that it is a "tadpole."



(4) The third life evolution, its tail and Gill disappeared, but also grow "four legs" and "lung", with legs and lung attributes, which eventually become a "frog."



Therefore, the object of the "class" is from scratch, and constantly evolve, and eventually disappeared in the intangible.



"Class" can indeed help us classify the world, but our minds cannot be bound by "class", and if life begins to be defined as a fixed "class", it cannot evolve, and a tadpole becomes a frog. Therefore, there is no "class" in JS, the class has been transformed into an invisible object and integration. It's closer to the real world, isn't it?



JS no class, JS object is a set of key value pairs, next look at the JS 9 kinds of ways to create objects.



The method of creating an object by JS is an iterative process, because the defects of existing methods have spawned new methods. First, the early JS programmers often use the simplest method--creating objects from the Objec constructor.



Creating objects from the object constructor



Code:



<script>

var person=new Object ();

Person.nam= "Lxy";

Person.age= "22";

person.job= "Software Engineer";

Person.sayname= function () {

alert (This.nam);

}

Person.sayname ();

</script>



Advantages: Simple



Third, create objects by literal volume



Code:



<script>

var person={

Name: "Lxy",

Age:22,

Job: "Software Engineer",


Sayname:function () {

alert (this.name);

}

};

Person.sayname ();

</script>



One thing to be aware of is that each declaration of a key value to the back punctuation is ",".



The object literal is a little less than the amount of the object constructor code. But these 2 methods create many objects through an interface, resulting in a lot of repetitive code. Don "T Repeat yourself! We need to abstract the duplicate code. This is where the factory pattern comes in.



Four, Factory mode



Creating multiple instances from a class necessarily reduces code duplication, but you cannot create classes in ECMAScript, so you use functions to encapsulate the details of creating objects with a specific interface.



Code:



<script>

function Createperson (name, age,job) {

var o=new Object ();

O.name=name;

O.age=age;

O.job=job;

O.sayname=function () {

alert (this.name);

}

return o;

}

var Lxy=createperson ("Lxy", "Software Engineer");

var Strangera=createperson ("Strangera", "Doctor");

Lxy.sayname ();

Strangera.sayname ();

</script>



Factory mode reduces duplicate code, but does not recognize objects, all instances are of type object.



This is when the constructor pattern appears.



Five, the constructor function pattern



Native constructors, such as object and array, automatically appear in the execution environment at run time. We can create custom constructors to create objects of a particular type.



Code:



<script>

function person (name, age,job) {

This.name=name;

This.age=age;

This.job=job;

This.sayname=function () {

alert (this.name);

}

}

var lxy=new person ("Lxy", "Software Engineer");

var strangera=new person ("Strangera", "Doctor");

Lxy.sayname ();

Strangera.sayname ();

</script>



The first letter in the constructor, rather than the first lowercase of the constructor, as the difference.



Create a person instance with the new operator, so that the instance created has a Constractor (constructor) attribute that points to person.



   alert (Lxy.constructor==person);//true     alert (strangera.constructor==person);//true




Lxy and Strangea are instances of person and also instances of object. Because all objects inherit from object.



Creating a custom constructor means that its instance can be identified as a specific type in the future, which is where the constructor trumps the factory pattern.



A constructor is also a function, so it can be used like a normal function, but can be used in a way that does not mean that it should be used, or as a constructor.



The problem with constructors is that the same method for different instances of the same constructor is not the same.



Alert (Lxy.sayname==strangera.sayname ());//false




This problem is well understood, because the function in JS is the object, each definition of a function, that is, the instantiation of an object.



From the point of view of the code may understand more profound:



This.sayname=function () {alert (this.name)};



This.sayname=New Function(Alert (this.name));



So you create objects using constructors, each method is to be implemented again on each instance , one is a resource, and the other is to create two or more functions that do not have the same function, and there is no need to bind it to a specific object before the code executes.



So, one way to do this is to move the function definition outside of the constructor, and the code is as follows:



<script>

function person (name, age,job) {

This.name=name;

This.age=age;

This.job=job;

This.sayname=sayname;

}

function Sayname () {

alert (this.name);

}

var lxy=new person ("Lxy", "Software Engineer");

var strangera=new person ("Strangera", "Doctor");

Lxy.sayname ();

Strangera.sayname ();

</script>



The definition of the Sayname () function is transferred to the outside of the constructor, which becomes the global function, and the sayname is set as the global Sayname within the constructor. So Sayname is a pointer to an external function, so lxy and Strangea share the global sayname function.



alert (lxy.sayname==strangera.sayname);//true




But there are worse questions: global scope functions can only be invoked by an object, which is not known to cause pollution to the global environment; What's worse is how many constructors have to define the number of global functions, and the constructor has nothing to encapsulate.



But the idea is valuable, paving the way for the prototype model, and the solution to the problem of creating objects in the constructor is the prototype pattern.



VI. PROTOTYPE Model



The prototype model is to take the method out of the constructor on the basis of in order to avoid pollution of the global environment, and then do a layer of encapsulation, but after all, is a new model, it encapsulates more thoroughly, and not all the functions are encapsulated, but just right to the constructor in the public Methods and properties are encapsulated.



Code:



<script type= "Text/javascript" >

function person () {


}

Person.prototype.name= "Lxy";

person.prototype.age=22;

person.prototype.job= "Software Engineer";

Person.prototype.sayname=function () {

alert (this.name);

}


var lxy=new person ();

Lxy.sayname ();

var persona=new person ();

Persona.sayname ();

Alert (Lxy.sayname () ==persona.sayname ());//true

</script>



The advantage of using prototypes is that all instances can share the properties and methods it contains. Solves the problem of the constructor perfectly. Because the prototype is a core content of JS, its information is very large, another introduction.



The stereotype also has its own problem, and if the shared property value is a reference type, the modification of an instance to that property affects other instances. This is why the prototype pattern is rarely used alone.



<script type= "Text/javascript"

Function person () {


}

Person.prototype.name= "Lxy";

person.prototype.age=22;

person.prototype.job= "Software Engineer";

person.prototype.friends=["Firend1", "Friend2"];

Person.prototype.sayname=function () {

    alert (this.name);

}

     

     var lxy=new person ();

     var Persona=new person ();

     alert (lxy.friends);//friend1,friend2

     alert ( persona.friends);//friend1,friend2

     alert (lxy.friends==persona.friends);//true

     Lxy.friends.push ("Friend3");

     alert (lxy.friends);//friend1,friend2,friend3

     alert ( persona.friends);//friend1,friend2,friend3

     alert (lxy.friends==persona.friends);// True

</script>



Seven, constructors and prototype blending mode



The most common way to create custom types is to combine the constructor pattern with the prototype pattern. The constructor pattern is used to define instance properties, which are used to define shared methods and properties. As a result, each instance has a copy of the instance attribute, while sharing a reference to the method, saving the maximum amount of memory. In addition, this hybrid mode also supports the transfer of parameters to the constructor, which is described as the length of the set of two modes.



Code:



<script type= "Text/javascript"

Function person (name,age,job) {

this.name=name;

This.age=age;

This.job=job;

this.friends=["Firend1", "Friend2"];

}


person.prototype={

    constructor:person,

    sayname:function () {

    alert (this.name);

}

}

     

     var lxy=new person ("Lxy", "Software Engineer" );

     var persona=new person ("persona", "Doctor");

     alert (lxy.friends);//friend1,friend2

     alert ( persona.friends);//friend1,friend2

     alert (lxy.friends==persona.friends);//false

     Lxy.friends.push ("Friend3");

     alert (lxy.friends);//friend1,friend2,friend3

     alert ( persona.friends);//friend1,friend2

</script>



Instance properties are defined in constructors, while shared properties constructor and shared methods Sayname () are defined in the prototype. Modifying the Friends of an instance does not affect the friends of other instances, because they refer to different arrays, and it doesn't matter.



The hybrid model of this constructor and prototype is one of the most widely used and most agreeable ways to create a custom type. It can be said that this is a default mode for defining reference types. In fact, the prototype is for the constructor service, with which to create objects, it is not advisable to create objects once and for all only through the prototype, because it creates shared properties and methods, and the rest is left to the constructor.



Eight, dynamic prototype mode



The individual feels that the constructor and prototype blending modes are already perfect for completing the task. But the dynamic prototyping model is proposed because the constructor object used in mixed mode has not yet been successfully created, and the prototype is needed, which is awkward for other OO language developers. So encapsulating all the information into the constructor, that is, initializing the prototype as necessary by the constructor, and using both the constructor and the prototype in the constructor, becomes the dynamic prototype pattern. When you really use it, you decide whether you need to initialize the prototype by checking whether a method that should exist is valid.



<script type= "Text/javascript" >

function Person (name,age,job) {

This.name=name;

This.age=age;

This.job=job;

this.friends=["Firend1", "Friend2"];

if (typeof this.sayname!= "function") {

Alert ("Initialize prototype");//Only once

Person.prototype.sayname=function () {

alert (this.name);

}

}

}


var lxy=new person ("Lxy", "Software Engineer");

Lxy.sayname ();

var persona=new person ("persona", "Doctor");

Persona.sayname ();

</script>



When using dynamic prototypes, you cannot use object literals to override prototypes. If you rewrite the prototype if you have already created an instance, you will sever the connection between the existing instance and the new prototype.



Nine, the parasitic structure function pattern



The parasitic (parasitic) constructor pattern is applicable in cases where the previous modes are not applicable. The parasitic pattern is to encapsulate the factory pattern in the constructor pattern by creating a function that simply encapsulates the code that creates the object and then returns the newly created object, which looks like a typical constructor on the surface.



Code:



<script type= "Text/javascript" >

function Person (name,age,job) {

var o=new Object ();

O.name=name;

O.age=age;

O.sayname=function () {

alert (this.name);

}

return o;

}

var lxy=new person ("Lxy", "Software Engineer");

Lxy.sayname ();

</script>



This pattern is identical to the factory pattern except that the new operator is used to make the function a constructor.



There is no relationship between the returned object and the constructor or the constructed stereotype property, so you cannot use instanceof, which creates an object that is no different from the object created outside the constructor.



Ten, the Safe mode of constructing function



A secure constructor pattern accesses an attribute using an explicitly declared method.



There is a concept associated with this pattern: a secure object. A Secure object is an object that does not have a public object and whose methods do not refer to this.



Secure objects are best used in some secure environments where this and new are disabled, or when data is changed by other applications, such as mashups.



A secure constructor follows a pattern similar to a parasitic constructor, but has two different points: one is that the instance method of the newly created object does not refer to this, but instead calls the constructor with the new operator.



Code:



<script type= "Text/javascript" >

function Person (name,age,job) {

Create the object to return

var o=new Object ();

You can define private variables and functions here


Add method

O.sayname=function () {

alert (name);

}

return o;

}

var lxy=new person ("Lxy", "Software Engineer");

Lxy.sayname ();

alert (lxy.name);//undefined

alert (lxy.age);//undefined

</script>



In an object created in this pattern, Lxy is a secure object, and there is no other way to access the value of name other than using the Sayname () method, Age,job is similar.



Even if there are other code that adds a method or data member to this object, there is no way to access the original data in the incoming constructor .



Similar to parasitic constructor patterns, objects created with a secure constructor pattern have little to do with constructors, and therefore cannot be used with the instanceof operator.








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.