The construction function of JS object-oriented programming

Source: Internet
Author: User

At the beginning of the last article, we said that there are two ways to create objects, one is the object constructor, and the other is the method of the Literal. however, creating multiple objects in these ways can result in a lot of duplicate code. Advances in technology have also evolved into many patterns of object Creation. This chapter introduces a mix of factory patterns, prototype patterns, constructor patterns, and constructors and prototype Patterns.

1, Factory mode

The factory model is a more well-known model that abstracts the Details. The code is as follows

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 person1=createperson ("ds", "dada"); var person2=createperson ("ds2", 122, "dada2");

Given the material he needed, he would return an object. Resolves a large number of duplicate code Issues. however, Another problem is that each returned object is A. The type part of each object does not come Out. So there's a new paradigm to solve this problem.

2, constructor Mode

Don't say much nonsense, let's go to the code First.

function person (name,age,job) {    this. name=name;      This. age= age;     this. job=job;     this. sayname=function() {        alert (this. Name)    }} var person1=New person ("ds", "dada"); var person2=New person ("ds2", 122, "dada2");

The second type uses the new Keyword. Actually went through 4 steps. 1, a new object is Created. 2, assign the scope of the constructor to the created Variable. 3, Execute the Code. 4, returns the new Object.

Person1 and Person2 are different instances. Two pairs like there is a constructor (constructor) that points to the Person's function itself. And constructor is the type used to represent Objects. This is also the difference between the constructor pattern and the factory Pattern. And think of object and array is JS native Constructor. Creating a custom constructor means that his instance can be identified as a specific type.

In fact, the constructor function is also the function of knowledge call different Way. Constructors can also be called in normal ways.

var p=New  Object (); Person.call (p,"sss", 22, "222");

But the constructor is not no problem, such as the above Sayname (), in fact, Person1 and Person2 Sayname is actually not the same funcition instance. In other words, the method of Sayname itself is new once for each new Object. The sayname of all instances are independent and do not point to the same method. The workaround also has the ability to extract the method to a global variable.

function person (name,age,job) {    this. name=name;      This. age= age;     this. job=job;     this. sayname=sayname;} function sayname () {    alert (this. name)}

But again, sayname as a global variable can only be called by person, a bit less in line with the definition of global variables. It is important to add a lot of methods to global variables if the methods are Many. fortunately, These problems can be solved by prototyping Patterns.

3, prototype mode

In the prototype model, you should first explain what prototype (prototype) is? It's actually a pointer to an Object. This object is a property and method that can be shared for all instances of a particular type. Let's look at the Code.

function person () {}person.prototype.name= "shaoqi"; Person.prototype.age=28; Person.prototype.job= "IT"; Person.prototype.sayName=function() {    alert (this. name);} var person1=New  pserson ();p erson1.sayname ();

Explains the relationships between objects, instances, prototypes, and Constructors.

In js, a prototype property is created for the function whenever a new function is Created. The prototype object that points to the Function. The prototype object will have a pointer to the constructor, pointing to the original Function. Each instance also has a pointer [[prototype]], pointing to the Prototype. In fact, each instance and constructor are not directly related, it is through the prototype to associate the instance and the Constructor.

In fact, the constructor has a simpler notation.

function person () {}person.prototype={    name:' Shaoqi ', age    : $,    job:' It ' ,    Sayname:function() {        alert (this. name);    }}

But then there is a problem, so quite with rewriting the whole prototype,js itself is not going to generate constructor for it. This means that there is no pointer to person in this prototype Object. But you can give it a value to show it.

function person () {}person.prototype={    constructor:person,    name:' Shaoqi ',    age :,    job:"It",    sayname:function() {        alert (  this. name);}    }

however, There is a small problem, that is, when this is displayed to the prototype to specify the constructor, its [[Enumerable]] will default to true, the native constructor cannot be Enumerated. If you must be compatible with ECMAScript5, you can write the following code

function person () {}person.prototype={    name:' Shaoqi ', age    : $,    job:' It ' ,    Sayname:function() {        alert (this. name);    }} Object.defineproperty (perosn.prototype,"constructor", {    enumerable:false,    Value:person})

DefineProperty This method is mentioned in the previous Paragraph. The method used to display the attribute of an assignment to a Property.

The prototype pattern also has a dynamic nature, which should exist for itself in the form of pointers in the Instance. You can dynamically add methods and properties to the Prototype. Can be dynamically added to the instance Above. of course, the prototype object is not perfect, there is a problem. Here's a look at the Code.

 function   person () {}person.prototype  ={constructor:person, name:  "shaoqi" , Age :  23 "It"  "11", "22" , "
       
       function  
        () {alert ( 
       this  
       .name); }}  
       var  person1=
       new  
        person ();  
       var  person2=
       new  
        person ();p erson1.friends.push ( "
        
      

The problem is that all instances (person1,person2) pointers point to an array. Person1 the data in the prototype after an array operation, the Person2 friend is Changed. The actual instance is generally to have all of their own properties. So that's why few people use the prototype mode Alone.

4, combining constructors and prototype patterns

Actually see here, we will find some problems of prototype pattern and tectonic Mode. The constructor pattern is that all of the properties are initialized for each instance one Out. The prototype mode is a property or method that is common to all instances. In fact, both methods are a bit extreme, in an object, in fact, the situation is diverse, some properties need to be independent, some need to share. All of this has the appearance of this combination Pattern. It is the length of the two Models.

function person (name,age,job) {    this. name=name;      This. age= age;     this. job=job;     this. friends=["one", "]}person.prototype" ={    constructor:person,    sayname:  function() {        alert (this. name);    }}

You will need to separate the attributes into the constructor for initialization, and then the properties of similar methods will be evaluated by the prototype method of Assignment.

This is the most widely used method of creating custom types in ECMAScript5.

5, Dynamic Prototype mode

In fact, there is no prototype in the object language such as C #, there is only one Constructor. In order to try to eliminate this difference, the dynamic prototype mode is Added. It just encapsulates all the information in the Constructor.

function person (name,age,job) {    this. name=name;      This. age= age;     this. job=job;     this. friends=["one", "a";     if (typeofthis. sayname! = "function")    {        Person.prototype.sayName=function() {            alert (this. Name)        }    }}

The difference is that there is a judgment in the Constructor. This judgment guarantees that the code inside is only run once during Initialization. This allows the same constructor to be used to complete the function of the combined Pattern.

6, Parasitic mode

This is a less-used pattern. In fact, he and the factory way is not much different. Look at 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 person1=New person ("dd", "dd");

Is it the same as the factory model?? The only difference is that when called, the parasitic pattern is initialized with the new method. What scenario does this model generally use?

Let's say we want to change it on the basis of the native array.

function specialarray () {    var value=New  Array ();    Value.push.apply (values,arguments);    value.topopedstring=function() {        returnthis. Join ("|" );    }     return value;} var colors=New specialarray ("one", "2", "n"); alert (colors.topopedstring ());

In the original type of transformation, you can use the parasitic mode, a bit similar to the extension in C #. however, the resulting instance and constructor are not related to the Prototype. So it is recommended that you do not use this mode without using it.

The constructor of the object is finished, and the principle of the prototype is SAID. The next article begins with the inheritance and prototype Chain.

JS constructor for object-oriented programming

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.