Javascript constructor mode, prototype mode

Source: Internet
Author: User

The first two days after writing the combination of inheritance, intends to summarize the prototype inherited, but today looked at the Factory mode, the constructor mode and prototype mode, I think it is necessary to summarize to deepen the impression.

—————————————————————————————————————————————————————————————————————————————————— shattered.

1. Factory mode

The advanced Programming of Javascript (3rd edition) introduces the factory model with a few 10 lines. I have found some relevant information to determine the specific application scenarios and advantages of this model. According to the data, it is considered that ECMAScript cannot create a class, so:

Create an object, then describe the properties and methods of the object, and then wrap it up as an interface with another object.

As described above, the factory function is used to implement functions similar to those in Java in Javascript. By calling the factory function, you can create multiple instances of similar objects.

Simple Factory mode: Use a class (usually a monomer) to generate an instance.
Complex Factory mode: Use subclasses to determine which instance of a particular class A member variable should be.

With regard to the advantages of Javascript using the factory model, according to the online summary, there are probably the following points:

A. Eliminating the coupling between objects (this is not quite clear, who is to be eliminated from whom?) );

B. In the case of batch-related settings, all instantiated code is concentrated in one place, helping to create modular code, reduce the amount of code;

C. Used for many small objects to form a large object.

Disadvantages:

A. There is no problem solving object recognition.

..... Let's keep this pattern for a while, without having a thorough advantage. After the understanding of the words to add. Quote from "Javascript design patterns and development practices" P5:

"In Javascript, which is a type of fuzzy language, object polymorphism is innate, and a variable can point to a class and can point to another class at any time. JavaScript does not have a type coupling problem, and naturally there is no need to deliberately "delay" the object to subclass creation, thatis, JavaScript does not actually require a factory method pattern . The existence of a pattern is the first thing that can solve a problem for us, this kind of forced simulation will only make people feel that design patterns are difficult to understand and useless. ”

2. Constructor mode

About encapsulation: In Javascript, you can encapsulate some properties and methods within a constructor;

About polymorphism: There is no overloaded concept in Javascript, but overloading can be simulated by the number of arguments and type judgments, but polymorphism is inherent in JavaScript. One of the simplest chestnuts:

The two object instances that are instantiated by the same constructor can pass different parameters to them, and the two object instances are different. This is the polymorphism of object-oriented programming.

With the constructor pattern, you can create multiple instances that are calibrated for a specific type. The constructor pattern is simpler and easier to implement than Factory mode, but there are drawbacks:

function Person (name,age,job) { This. Name =name;  This. Age =Age ;  This. Job =job;  This. arr = [];  This. Sayname =function () {alert ( This. Name); };}varPerson1 =NewPerson ("Nicholas", in,"Software Engineer");varPerson2 =NewPerson ("Greg", -,"Doctor"); Console.log (Person1.sayname==person2.sayname);//falsePerson1.arr.push (1); Console.log (Person1.arr);//1Person2.arr.push (2); Console.log (Person2.arr);//2

Each instance of an instance object is instantiated with a constructor, and the methods within the constructor are recreated on the instance. The returned results returned by Person1.sayname==person2.sayname can be seen differently than the two instance references.

Note: This also applies to arrays.

You can make the object instance refer to the same method each time by placing the constructor's method externally.

functionPerson (name,age,job) { This. Name =name;  This. Age =Age ;  This. Job =job;  This. Sayname =Sayname;}functionSayname () {alert ( This. name);}varPerson1 =NewPerson ("Nicholas", "Software Engineer");varPerson2 =NewPerson ("Greg", "Doctor"); Console.log (Person1.sayname==person2.sayname);//true

By referring the method of the constructor to the external as: Privileged method. You can make the instance get the same method reference.

But there are some problems with this approach: referring to external methods as privileged methods makes encapsulation worse. If there are many methods within the constructor, the consequences are more pronounced.

Another question: if there are multiple fixed properties within the constructor, and there are multiple methods. When instantiating, you copy the same fixed properties for each object, and if you place the method inside the constructor, the methods are duplicated, even if they are privileged functions.

In summary, there are two insufficient points in the constructor mode: 1. Waste memory; 2. May cause the encapsulation to become worse.

3. Prototype mode

The appearance of prototype pattern solves the problem of duplicate deep copy of fixed attribute method during constructor instantiation.

For the same properties and methods, an instance of the constructor can share the same property and method whenever it is declared on the prototype object of the constructor.

function= "Nicholas"function() {    Console.log (this. Name) );} var New Person (); var New Person (); Console.log (Person1.sayname===person2.sayname); // trueconsole.log (person1.name===person2.name); // true

4. Combining the constructor pattern with the prototype mode (mixed mode)

However, although the prototype pattern can solve the problem of multiple copies of fixed properties and methods, if the properties are to be changed according to different instance objects, it is better to place the attributes that will change with the instance object inside the constructor, which in turn uses the constructor pattern. By combining the constructor pattern with the prototype pattern, you can take advantage of these two patterns.

functionPerson (name,age) {//properties that will change with the instance object     This. Name =name;  This. Age =Age ;}//Invariant properties or methodsPerson.prototype.job = "Soft Engineer"; Person.prototype.sayName=function() {Console.log ( This. name);}varPerson1 =NewPerson ("Nicholas", 28);varPerson2 =NewPerson ("Shelby", 25);

Javascript constructor mode, prototype mode

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.