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

What is object orientation? Object orientation is an idea! (nonsense).


  Object-oriented can treat the key modules in the program as objects, and modules have properties and methods. In this way, if we encapsulate some properties and methods, it will be very convenient to use in the future, and it can also avoid tedious and repetitive work. Next, I will explain the object-oriented implementation in JS.


   Factory Pattern The


  factory pattern is a well-known design pattern in the field of software engineering, and since classes cannot be created in ECMAScript, functions are encapsulated to create objects with specific interfaces. The implementation method is very simple, that is, create an object in the function, assign properties 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/');
 


It can be seen that the implementation method of the factory mode is very simple, which solves the problem of creating multiple similar objects, but the factory mode cannot identify the object Type, because all are Object, unlike Date, Array, etc., so the constructor pattern appears.


  Constructor Mode Constructors


  in ECMAScript can create specific types of objects, similar to native JS objects such as Array and Date. Its 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, to determine whether blog is an instance of Blog, that is, it solves the problem of factory mode.
 


This example is different from factory mode except for the function name. , careful children's shoes should find many differences:


the first letter of the function name is uppercase (although the standard does not strictly stipulate that the first letter is uppercase, but by convention, the first letter of the constructor is capitalized
 . The created object does not show the
 property directly And the method is assigned to the this object.
 There is no return statement
 . Creating an object using new
 can identify the object (this is where the constructor pattern is better than the factory pattern).


  Although the constructor is easy to use, it is not without its shortcomings. The biggest problem with using the constructor The method is to be recreated every time an instance is created (in theory, the properties of the object are different each time an object is created, and the method of the object is the same), but it is not necessary to create the exact same method twice. So we can move the function out of the object (maybe some kids already see the downside, shhh!).


 
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 as a global function, so that blog and blog2 access the same function, but the problem comes again, defined in the global scope A function that actually only wants to be used by Blog shows that the global scope is somewhat worthy of its name. What is even more unacceptable is that there are many methods defined in the global scope that are only used by specific objects. Objects are encapsulated, so prototypes can be used to solve this problem.


  Prototype Pattern Every function


  we create has a prototype property, which is a pointer to an object whose purpose is to contain properties and methods that can be shared by all instances of a particular type. The advantage of using prototype objects is that all object instances can share the properties and methods it contains.


 
function Blog() {
}
 
Blog.prototype.name = 'wuyuchang';
Blog.prototype.url = 'http://tools.jb51.net/';
Blog.prototype.friend = ['fr1', 'fr2', 'fr3', 'fr4'];
Blog.prototype.alertInfo = function() {
  alert(this.name + this.url + this.friend );
}
 
// 以下为测试代码
var blog = new Blog(),
  blog2 = new Blog();
blog.alertInfo();  // wuyuchanghttp://tools.jb51.net/fr1,fr2,fr3,fr4
blog2.alertInfo();  // wuyuchanghttp://tools.jb51.net/fr1,fr2,fr3,fr4
 
blog.name = 'wyc1';
blog.url = 'http://***.com';
blog.friend.pop();
blog2.name = 'wyc2';
blog2.url = 'http://+++.com';
blog.alertInfo();  // wyc1http://***.comfr1,fr2,fr3
blog2.alertInfo(); // wyc2http://+++.comfr1,fr2,fr3
 


prototype mode is not without its shortcomings, first of all, it omits the link that the constructor passes initialization parameters, and all instances are by default It is very inconvenient to obtain the same property value, but this is not the biggest problem of prototype. The biggest problem of prototype mode is caused by the nature of sharing. Because of sharing, one instance modifies the reference, and the other also follows. Changed citations. Therefore, we usually do not use prototypes alone, but combine the prototype pattern with the constructor pattern.


  Mixed 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();
blog2.alertInfo(); // wychttp://**.coma,b In the
 




mixed mode, the constructor mode is used to define instance properties, while the prototype mode is used to define methods and shared properties. Each instance will have its own instance attributes, but at the same time share methods, which saves memory to the greatest extent. In addition, this mode also supports passing initial parameters. There are many advantages. This pattern is the most widely used and recognized method of creating custom objects in ECMAScript.


  Dynamic prototype mode The


  dynamic prototype mode encapsulates all information in the constructor, and initializes the prototype in the constructor (only the prototype is initialized when the first object is instantiated). This can be determined by judging whether the method is valid and whether the prototype needs to be initialized .




 
function Blog(name, url) {
  this.name = name;
  this.url = url;
 
  if (typeof this.alertInfo != 'function') {
    // this code is only executed once
    alert('exe time');
    Blog.prototype.alertInfo = function() {
      alert(thia.name + this.url);
    }
  }
}
 
var blog = new Blog('wuyuchang', 'http://tools.jb51.net'),
  blog2 = new Blog('wyc', 'http:
 


It can be seen that the window pops up only once in the above example, 'exe time', that is, when the blog is initialized, blog2 does not need to initialize the prototype in this way. It can be regarded as perfect for creating objects using this mode.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325780418&siteId=291194637