JS object-oriented Basics (factory mode, Constructor mode, prototype mode, mixed mode, dynamic prototype Mode)

Source: Internet
Author: User

What is object-oriented? object-oriented is an Idea.

Object-oriented can treat the key modules in the program as objects, while the modules have properties and METHODS. This way, if we encapsulate some properties and methods, it will be very convenient to use in future and avoid tedious duplication of Work. Factory modeFactory mode is a well-known design pattern in the field of software engineering, and because ECMAScript cannot create classes, it uses function encapsulation to create objects with specific Interfaces. the implementation method is very simple, which is to create an object within the function that gives the object the property and method to return the Object.
1 /**2 * Factory mode3 * Advantages: Solve the problem of creating objects4 * Cons: No problem solving object recognition problems instanceof-5  * */6 functionCreateperson (name, age, job) {7     varo =NewObject ();8O.name =name;9O.age =age ;TenO.job =job; oneO.sayname =function(){ aConsole.log ( this. name); -     }; -     returno; the } -  - varPerson1 = Createperson ("xialiu", "shijiazhuang"); - varPerson2 = Createperson ("xiaobei", "hainan"); + Console.log (person1); -Console.log (person2);
You can see that the implementation of the factory pattern is very simple and solves the problem of creating multiple similar objects. but the engineering pattern is missing the type of the object, because it is all object, not like date, array, etc., so a constructor pattern Appears.
Constructor mode
The constructors in ECMAScript can create objects of a specific type, similar to native JS objects such as array, date, and so on. it is implemented as Follows:
1 /**2 * Constructor Mode3 * Advantages: Solve the problem of object recognition4 * Cons: functions with the same name on different instances are not equal. there is a This object in, there is no need to execute the code before the function to bind to a specific object.5  * */6 functionBlog (name,url) {7      this. Name =name;8      this. url =url;9      this. Alerturl =function () {Ten Console.log (alerturl); one     } a } - varBlog =NewBlog ("xiaomeng", "HTTP://www.baidu.com/"); -Console.log (bloginstanceofBlog);//true, Determines whether the blog is an instance of the blog, that is, to solve the Factory mode can not theConsole.log (blog);
This example and the factory model in addition to the function of the name of different, careful students should find a lot of differences.
Function name handwritten letter Capitalization---although The standard does not strictly specify the capitalization of handwritten letters, it is customary to capitalize the first letter of the Constructor.
Create an object without a first time
Assigning properties and methods directly to the This object
No return statement
Create an object using new
Ability to recognize objects, which is where the constructor pattern is better than the factory pattern
Although the constructor works well, it is not without its drawbacks, the biggest problem with using constructors is to recreate the method each time the instance is created (theoretically, each time the object is created with different properties, and the Object's method is the same), however, it is not necessary to create two identical methods, We can move the function out of the Object.
1 functionBlog (name, Url) {2      this. Name =name;3      this. url =url;4      this. Alerturl =alerturl;5 }6 functionAlerturl () {7Console.log ( this. url);8 }9 varBlog =NewBlog ("xiaokeai", "http://www.xiaokeai.com/"), blog2 =NewBlog ("xiaomeinv", "http://www.123.com/");Ten Blog.alerturl (); oneBlog2.alerturl ();
We set the Alerturl to a global function, so that the blog and BLOG2 access are all the same function, but the problem comes again, in the global scope to define a real just want to let the blog use the function, display let the global scope some veritable, What is even more unacceptable is that many methods are defined in the global scope that are used only for specific objects, wasting space, and obviously losing object-oriented encapsulation, so you can solve this problem by prototyping.
Prototype mode
Each function we create has a prototype property, which is a pointer to an object that is used to contain properties and methods that can be shared by all instances of a particular type. the advantage of using a prototype object is that you can have all of the object instances share the properties and methods that it contains.
1 /**2 * Prototype Mode3  * */4 functionBlog () {5Blog.prototype.name = "xiaomeiren";6Blog.prototype.url = "http://www.xiaomeiren.com/";7Blog.prototype.friend = ["aaa", "bbb", "ccc", "ddd", "eee"];8Blog.prototype.alertInfo =function () {9Console.log ( this. Name + "+ this. URL + ' + this. friend);Ten     } one } a varBlog =NewBlog (), blog2 =NewBlog (); -Blog.alertinfo ();//"xiaomeiren http://www.xiaomeiren.com/aaa,bbb,ccc,ddd,eee" -Blog2.alertinfo ();//"xiaomeiren http://www.xiaomeiren.com/aaa,bbb,ccc,ddd,eee" the  -Blog.name = "xiaomeiyun"; -Blog.url = "http://www.xiaomeiyun.com/"; - Blog.friend.pop (); +  -Blog2.name = "xiaomeiyun2"; +Blog2.url = "http://www.xiaomeiyun2.com/"; a  atBlog.alertinfo ();//"xiaomeiyun http://www.xiaomeiyun.com/aaa,bbb,ccc,ddd" -Blog2.alertinfo ();//"xiaomeiyun2 http://www.xiaomeiyun2.com/aaa,bbb,ccc,ddd"
Prototype mode is not without shortcomings, first of all, it ignores the constructor passed the initialization parameters of the link, the result all instances by default, the same property values have been obtained, this is very inconvenient, but this is not the biggest problem of the Prototype. the biggest problem with prototype mode is the nature of sharing, which is caused by sharing, So one instance modifies the reference, and the other modifies the reference. therefore, we usually do not use the prototype alone, but combine the prototype pattern and the constructor Pattern.
Mixed mode
Blending mode is the prototype mode plus the constructor mode
1 /**2 * Mixed Mode = prototype Mode + constructor mode3  * */4 functionBlog (name, url, friend) {5      this. Name =name;6      this. url =url;7      this. Friend =friend;8 }9 TenBlog.prototype.alertInfo =function () { oneConsole.log (' name: ' + this. Name + ' Blog: ' + this. URL + ' friends: ' + this. friend); a } -  - varBlog =NewBlog ("liming", "http://www.limingweb.com/", ["aaa", "bbb", "ccc", "ddd")]), theBLOG2 =NewBlog ("limingming", "http://www.limingmingweb.com/", ["aaa", "bbb", "ccc", "ddd")]); -Blog.friend.pop ();//the Arrayobject.pop () method is used to delete and return the last element of the array, and the array length is reduced by 1. -Blog.alertinfo ();//name: liming blog: http://www.limingweb.com/friends: AAA,BBB,CCC -Blog2.alertinfo ();//name: limingming blog: http://www.limingmingweb.com/friends: aaa,bbb,ccc,ddd
The constructor pattern in mixed mode is used to define instance properties, whereas the prototype pattern is used to define methods and shared Properties. Each instance will have its own instance attribute, but at the same time share this method to maximize memory savings. This mode also supports the transfer of initial Data. this model uses a wide range of the most recognized methods for creating custom Objects.
Dynamic Prototyping Mode
The dynamic prototype pattern encapsulates all the information in the constructor, and by initializing the prototype in the constructor, it is possible to choose whether or not to initialize the prototype by judging whether the method is Valid.
1 functionBlog (name, Url) {2      this. Name =name;3      this. url =url;4     if(typeof  this. alertinfo! = "function"){5         //This code executes only once6Console.log ("haha");7Blog.prototype.alertInfo =function () {8Console.log (' name: ' + this. Name + ' Blog: ' + this. url);9         }Ten     } one } a varBlog =NewBlog ("liming", "http://www.limingweb.com/"), -BLOG2 =NewBlog ("limingming", "http://www.limingmingweb.com/");
Operation effect; haha
That is, when the blog is initialized, this blog2 no longer need to initialize the prototype, for this mode to create objects, is already very perfect.

JS object-oriented Basics (factory mode, Constructor mode, prototype mode, mixed mode, dynamic 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.