You don't know. JAVASCRIPT--ITEM25 8 ways to create objects (classes) Summary

Source: Internet
Author: User
Tags function definition

1. Use the object constructor to create an object

The following code creates a person object and prints out the property value of name in two ways.

    varnewObject();    person.name="kevin";    person.age=31;    alert(person.name);    alert(person["name"])

Another manifestation of the above notation is to use object literals to create an object, not surprisingly person["5", which is legal, and there are spaces between fields such as person["my Age").

var person =     {        name:"Kevin",        age:31,        5:"Test"    };    alert(person.name);    alert(person["5"]);

Although the object constructor or object literal can be used to create a single object, there are obvious drawbacks to these approaches: creating many objects using the same interface creates a lot of duplicate code. to solve this problem, people began to use a variant of the factory model.

2. Factory mode

Factory mode is a well-known design pattern in the field of software engineering, which abstracts the process of creating concrete objects, considering the inability to create classes in ECMAScript, developers invent a function that encapsulates the details of creating objects with specific interfaces, as shown in the following example.

 function createperson(name, age, Job){    varo =New Object();    O.name = name;    O.age = age;    O.job = job; O.sayname = function(){Alert This. name); };returno;}varPerson1 = Createperson ("Nicholas", in,"Software Engineer");varPerson2 = Createperson ("Greg", -,"Doctor");

Factory mode solves the problem of creating multiple similar objects, but does not solve the problem of object recognition (that is, how to know the type of an object). with JavaScript
Development, another new paradigm has emerged.

3. Constructor mode

Constructors such as object and array are automatically present in the execution environment at run time. In addition, you can create custom constructors that define properties and methods for custom object types. For example, you can use the constructor pattern to rewrite the preceding example as follows.

 function person(name, age, Job){     This. name = name; This. Age = Age; This. Job = job; This. Sayname = function(){Alert This. name);};}varPerson1 =NewPerson ("Nicholas", in,"Software Engineer");varPerson2 =NewPerson ("Greg", -,"Doctor");

In this example, the person () function replaces the Createperson () function. We note that the code in person () has the following differences in addition to the same parts in Createperson ():

    • 1, not explicitly create objects;
    • 2, directly assigns the attribute and the method to this object;
    • 3, no return statement.

To create a new instance of person, you must use the new operator. Calling a constructor in this way actually goes through the following 4 steps:

    • (1) Create a new object;
    • (2) assigns the scope of the constructor to the new object (so this points to the new object);
    • (3) Executing the code in the constructor (adding attributes to the new object);
    • (4) Returns the new object.

At the end of the previous example, Person1 and Person2 each hold a different instance of person. Both objects have a constructor (constructor) property that points to person, as shown below.

alert(person1.constructor//truealert(person2.constructor//true

The constructor property of an object is originally used to identify the object type. However, it is more reliable to refer to the detection object type or the instanceof operator. All of the objects we create in this example are both instances of object and instances of person, which can be verified by the instanceof operator.

instanceofObject//trueinstanceof//trueinstanceofObject//trueinstanceof//true

Creating a custom constructor means that its instance can be identified as a specific type in the future, which is where the constructor pattern is better than the factory pattern. In this example, Person1 and Person2 are both instances of object because all objects inherit from object.

Problems with constructors

The constructor mode is useful, but it is not without drawbacks. The main problem with constructors is that each method is recreated on each instance.

A function in ECMAScript is an object, so every definition of a function is an instantiation of an object. From a logical point of view, constructors can also be defined this way.

function Person(name, age, job){    this.name = name;    this.age = age;    this.job = job;    thisnewFunction("alert(this.name)"// 与声明函数在逻辑上是等价的}

From this perspective, it is easier to see that each person instance contains a different function instance (to display the Name property). To be clear, creating a function in this way causes a different scope chain and identifier resolution, but the mechanism for creating a new instance of a function is still the same. As a result, functions with the same name on different instances are not equal, as the following code can attest.

alert(person1.sayName == person2.sayName); //false

However, it is not necessary to create two function instances that accomplish the same task, and there is no need to bind the function to a particular object before executing the code. Therefore, it is possible to solve this problem by moving the function definition outside the constructor as follows.

 function person(name, age, Job){     This. name = name; This. Age = Age; This. Job = job; This. Sayname = Sayname;} function sayname(){Alert This. name);}varPerson1 =NewPerson ("Nicholas", in,"Software Engineer");varPerson2 =NewPerson ("Greg", -,"Doctor");

If an object needs to define many methods, it is necessary to define many global functions, so we have no encapsulation of this custom reference type. Fortunately, these problems can be solved by using prototype mode.

4. Prototype mode
function  person   ()  {}person.prototype.name = " Nicholas "; Person.prototype.age = 29 ; Person.prototype.job =  "software Engineer" ; Person.prototype.sayName = function   ()  { alert (this . name);}; var  person1 = new  person ();p erson1.sayname (); //"Nicholas"  var  person2 = new  person ();p erson2.sayname (); //"Nicholas"  alert (person1.sayname = = Person2.sayname); //true  

To understand the prototype object, see my other Blog: JavaScript prototype detailed

In the previous example, every property and method you add will be knocked over Person.prototype. To reduce unnecessary input and to visually better encapsulate the functionality of the prototype, it is more common to rewrite the entire prototype object with an object literal that contains all the properties and methods, as shown in the following example.

function Person(){}Person.prototype = {    "Nicholas",    29,    "Software Engineer",    function () {        alert(this.name);    }};

In the above code, we set the person.prototype to equal to a new object created as an object literal. The end result is the same, with one exception: the constructor property no longer points to person. As described earlier, each time you create a function, it creates its prototype object, which also automatically gets the constructor property. The syntax we use here essentially completely overrides the default prototype object, so the constructor property becomes the constructor property of the new object (pointing to the object constructor) and no longer points to the person function. At this point, although the instanceof operator can return the correct result, the type of the object cannot be determined by constructor, as shown below.

varnewinstanceofObject//trueinstanceof//true//falseObject//true

Here, the instanceof operator is used to test that object and person still return true, but the constructor property is equal to object and not equal to person. If the value of constructor is really important, you can deliberately set it back to the appropriate value as follows.

function Person(){}    Person.prototype = {    constructor : Person,    "Nicholas",    29,    "Software Engineer",    function () {        alert(this.name);    }};

One thing to note is that the pointer in the instance points only to the prototype, not to the constructor.

Problem with prototype objects: Prototype mode is not without drawbacks. First, it omits the process of passing initialization parameters to the constructor, resulting in all instances getting the same property value by default. While this will somehow bring some inconvenience, it's not the biggest problem with prototypes. The biggest problem with prototype patterns is the nature of their sharing.

 function person(){}person.prototype = {Constructor:person, name:"Nicholas", Age: in, Job:"Software Engineer", Friends: ["Shelby","Court"], Sayname: function () {Alert This. name); }};varPerson1 =NewPerson ();varPerson2 =NewPerson ();p Erson1.friends.push ("Van"); alert (person1.friends);//"Shelby,court,van"alert (person2.friends);//"Shelby,court,van"Alert (person1.friends = = = Person2.friends);//true
5. Combination of constructor mode and prototype mode (most commonly used)

The most common way to create a custom type is to combine the constructor pattern with the prototype pattern. The constructor pattern is used to define instance properties, and the prototype schema is used to define methods and shared properties. As a result, each instance will have its own copy of the instance properties, but at the same time it shares a reference to the method, saving the memory to a minimum. In addition, this blending pattern also supports passing parameters to the constructor, which is the length of the two modes.

 function person(name, age, Job){     This. name = name; This. Age = Age; This. Job = job; This. Friends = ["Shelby","Court"];} Person.prototype = {Constructor:person, sayname: function(){Alert This. name); }}varPerson1 =NewPerson ("Nicholas", in,"Software Engineer");varPerson2 =NewPerson ("Greg", -,"Doctor");p Erson1.friends.push ("Van"); alert (person1.friends);//"Shelby,count,van"alert (person2.friends);//"Shelby,count"Alert (person1.friends = = = Person2.friends);//falseAlert (Person1.sayname = = = Person2.sayname);//true
6. Dynamic prototype mode

Developers with other OO language experiences are likely to be very confused when they see independent constructors and prototypes. The dynamic prototyping model is a solution to this problem by encapsulating all the information in the constructor, and by initializing the prototype in the constructor (only if necessary), while preserving the advantages of using both constructors and prototypes. In other words, you can determine whether a prototype needs to be initialized by checking that a method that should exist is valid. Take a look at an example.

 function person(name, age, Job){    //Properties     This. name = name; This. Age = Age; This. Job = job;//Method---------------------------------------------if(typeof  This. sayname! ="function") {Person.prototype.sayName = function(){Alert This. name);    }; }    --------------------------------------------    }varFriend =NewPerson ("Nicholas", in,"Software Engineer"); Friend.sayname ();
7. Parasitic structural function mode

In general, the parasitic (parasitic) constructor pattern can be used in situations where none of the aforementioned modes are applicable. The basic idea of this pattern is to create a function that encapsulates the code that creates the object, and then returns the newly created object, but on the surface, the function looks like a typical constructor. Here is an example.

function  person   (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  friend = new  person (  "Nicholas" , 29 ,  " Software Engineer "); Friend.sayname (); //"Nicholas"   

In this example, the person function creates a new object, initializes the object with the appropriate properties and methods, and then returns the object. In addition to using the new operator and using the wrapper function called the constructor, this pattern is exactly the same as the factory pattern. The constructor returns a new object instance by default, without returning a value.

8. Secure Structural function mode

The so-called secure object refers to the absence of a public property, and its method does not refer to the object of this. Secure objects are best suited for use in some secure environments where this and new are prohibited, or when data is being altered by other applications, such as mashup programs. The secure constructor follows a pattern similar to the parasitic constructor, but has a difference of two points: one is that the instance method of the newly created object does not refer to this, and the second is not to call the constructor with the new operator. The preceding person constructor can be rewritten as follows, as required by the secure constructor.

function Person(name, age, job){    //创建要返回的对象    varnewObject();    //可以在这里定义私有变量和函数    //添加方法    function(){        alert(name);    };//返回对象return o;}

Copyright NOTICE: This article is the original article, reproduced please specify: http://blog.csdn.net/i10630226

You don't know. JAVASCRIPT--ITEM25 8 ways to create objects (classes) Summary

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.