JS object-oriented basic explanation (factory mode, constructor mode, prototype mode, hybrid mode, dynamic prototype mode) _ javascript skills

Source: Internet
Author: User
This article mainly introduces the basic explanation of object-oriented JS, such as the factory mode, constructor mode, prototype mode, hybrid mode, and dynamic prototype. If you need it, What Is Object-Oriented? Object-oriented is an idea! (Nonsense ).

Object-oriented can regard all key modules in the program as objects, and the module has attributes and methods. In this way, if we encapsulate some attributes and methods, it will be very convenient to use in the future and avoid tedious and repetitive work. Next we will explain how to implement object-oriented in JS.

Factory Model

The factory model is a well-known design model in the software engineering field. Because classes cannot be created in ECMAScript, function encapsulation is used to create objects with specific interfaces. The implementation method is very simple, that is, to create an object in the function, assign attributes and methods to the object, and then return the object.

function createBlog(name, url) {  var o = new Object();  o.name = name;  o.url = url;  o.sayUrl= function() {    alert(this.url);  }  return o;}var blog1 = createBlog('wuyuchang', 'http://www.jb51.net/');

We can see that the implementation method of the factory mode is very simple and solves the problem of creating multiple similar objects, but the factory mode cannot identify the Object type, because all objects are objects, unlike Date and Array, the constructor mode appears.

  Constructor Mode

ECMAScript constructor can create specific types of objects, similar to native JS objects such as Array and Date. The implementation method is as follows:

Function Blog (name, url) {this. name = name; this. url = url; this. alertUrl = function () {alert (this. url) ;}} var blog = new Blog ('wuyuchang', 'HTTP: // www.jb51.net/'); console. log (blog instanceof Blog); // true, judge whether the blog is a Blog instance, that is, the factory mode cannot

In this example, apart from the function name in the factory model, we should find many differences between the careful kids shoes:

The first letter of the function name is capitalized (although the standard does not strictly stipulate that the first letter is capitalized, according to the Convention, the first letter of the constructor is capitalized)
No created object is displayed
The attribute and method are directly assigned to this object.
No return Statement
Use new to create an object
Ability to recognize objects (this is where the constructor mode is better than the factory Mode)

Although the constructor is easy to use, it does not have any disadvantages, the biggest problem with using constructor is that the method needs to be re-created every time an instance is created (theoretically, the object attributes are different each time an object is created, the object methods are the same). However, it is unnecessary to create two identical methods. Therefore, we can move the functions out of the object (maybe some children's shoes have seen the disadvantages, hey !).

function Blog(name, url) {  this.name = name;  this.url = url;  this.alertUrl = alertUrl;}function alertUrl() {  alert(this.url);}var blog = new Blog('scjb51', 'http://sc.jb51.net/'),  blog2 = new Blog('jb51', 'http://www.jb51.net/');blog.alertUrl();  // http://sc.jb51.net/blog2.alertUrl();  // http://www.jb51.net/

We set alertUrl to a global function, so that both the blog and blog2 access the same function, but the problem arises again. In the global scope, we define a function that actually only needs to be used by the Blog, display makes the global scope a bit real. What is even more unacceptable is that many methods are defined in the global scope for specific objects only, which is a waste of space, the object-oriented encapsulation is obviously lost, so this problem can be solved through prototype.

 Prototype

Each function we create has the prototype attribute, which is a pointer pointing to an object, the purpose of this object is to include attributes and methods that can be shared by all instances of a specific type. The advantage of using a prototype object is that all object instances can share its attributes and methods.

Function Blog () {} Blog. prototype. name = 'wuyuchang'; Blog. prototype. url = 'HTTP: // tools.jb51.net/'your blog.prototype.friend = ['fr1', 'fr2', 'fr3', 'fr4']; Blog. prototype. alertInfo = function () {alert (this. name + this. url + this. friend);} // The following is the test code var blog = new Blog (), blog2 = new Blog (); blog. alertInfo (); // wuyuchanghttp: // response (); // wuyuchanghttp: // tools.jb51.net/fr1,fr2,fr3,fr4blog.name = 'wyc1 '; blog. url = 'HTTP ://***. com '; blog. friend. pop (); blog2.name = 'wyc2'; blog2.url = 'HTTP: // ++. com '; blog. alertInfo (); // wyc1http ://***. comfr1, fr2, fr3blog2. alertInfo (); // wyc2http: // ++. comfr1, fr2, fr3

The prototype mode does not have any disadvantages. First, it omits the process of passing initialization parameters through the constructor. As a result, all instances obtain the same attribute values by default, which is inconvenient, however, this is not the biggest problem of the prototype. The biggest problem of the prototype mode is the sharing nature. Because of the sharing, one instance modifies the reference and the other changes the reference. Therefore, we usually do not use the prototype separately, but combine the prototype mode with the constructor mode.

  Hybrid mode (prototype mode + constructor Mode)

function Blog(name, url, friend) {  this.name = name;  this.url = url;  this.friend = friend;}Blog.prototype.alertInfo = function() {  alert(this.name + this.url + this.friend);}var blog = new Blog('wuyuchang', 'http://tools.jb51.net/', ['fr1', 'fr2', 'fr3']),  blog2 = new Blog('wyc', 'http://**.com', ['a', 'b']);blog.friend.pop();blog.alertInfo();  // wuyuchanghttp://tools.jb51.net/fr1,fr2blog2.alertInfo();  // wychttp://**.coma,b

In mixed mode, the constructor mode is used to define instance attributes, while the prototype mode is used to define methods and shared attributes. Each instance has its own instance attribute, but it also shares the method to maximize memory savings. In addition, this mode also supports passing initial parameters. There are many advantages. In ECMAScript, this mode is the most widely used method for creating custom objects with the highest degree of consistency.

  Dynamic Prototype

The dynamic prototype mode encapsulates all information in the constructor, and initializes the prototype through the constructor (only the prototype is initialized when the first object is instantiated ), you can determine whether the method is valid and choose whether to initialize the prototype.

Function Blog (name, url) {this. name = name; this. url = url; if (typeof this. alertInfo! = 'Function') {// This Code only executes alert ('exe Time') once; Blog. prototype. alertInfo = function () {alert (thia. name + this. url) ;}} var blog = new Blog ('wuyuchang', 'HTTP: // tools.jb51.net'), blog2 = new Blog ('wyc', 'HTTP: ***. com ');

We can see that in the above example, only one window pops up, 'exe time', that is, when the blog is initialized, blog2 does not need to initialize the prototype. For object creation in this mode, it can be called perfect.

This blog post references JavaScript advanced programming 3rd, but the language has been simplified and the example has been rewritten. If you have any questions, please leave a message and reply. The author will update the blog.

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.