JS object-oriented Basic Explanation (Factory mode, constructor mode, prototype model, mixed mode, dynamic prototype mode) _javascript skills

Source: Internet
Author: User
Tags mixed

What is Object oriented? Object oriented is an idea! (nonsense).

Object-oriented can treat key modules in a program as objects, and modules have 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 duplication of work. Next, we will explain the object-oriented implementation in JS.

Factory mode

The factory model is a well-known design pattern in the Software engineering field, and because classes cannot be created in ECMAScript, they are encapsulated with functions to create objects with a specific interface. The implementation method is very simple, that is, create an object within the function, give the object attributes and methods 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/');

You can see that the implementation of the factory pattern is very simple and solves the problem of creating multiple similar objects, but the factory pattern does not recognize the object's type because it is all object, unlike date, array, and so on, so the constructor pattern appears.

  Constructor pattern

A constructor in ECMAScript can create a specific type of object, similar to an array, date, and other native JS objects. 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 to determine whether a blog is an instance of a blog, that is, to solve the Factory mode can not

This example is different from the factory model in addition to the function name, careful child shoes should find many different places:

The first letter of the function name is uppercase (although the standard does not strictly specify that the initials are uppercase, it follows that the constructor's initials are capitalized
Create object not shown
Assigning properties and methods directly to the This object
No return statement
Create an object with new
Able to identify objects (this is where the constructor pattern is better than the factory pattern)

constructors, while useful, are not without drawbacks, the biggest problem with constructors is that each time you create an instance, you re-create the method (in theory, the object's properties are different each time you create the object, and the object's method is the same), but it is not necessary to create the exact same method two times. We can move the function out of the object (maybe some of the children's shoes have seen the flaw, Shh!) )。

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 the Alerturl as a global function, so that the blog and BLOG2 access are the same function, but the problem again, in the global scope of the definition of a real only want to use the blog function, show that the global scope of some worthy, 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 (prototype) attribute, which is a pointer to an object that is intended 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 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);
}

The following is the test code
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 model is not without drawbacks, first of all, it omits the link of constructor pass initialization parameter, the result all instances have obtained the same attribute value by default, this is very inconvenient, but this is not the biggest problem of the prototype, the biggest problem of the prototype pattern is that the shared nature causes, because of sharing, So one instance modifies the reference, and the other changes the reference. Therefore, we usually do not use the prototype alone, but combine the prototype pattern with the constructor pattern.

  Blending 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,FR2
blog2.alertinfo ();  Wychttp://**.coma,b

The constructor pattern in mixed mode is used to define instance properties, and the stereotype pattern is used to define methods and shared properties. Each instance has its own instance attribute, but at the same time it shares the method to maximize memory savings. In addition, this pattern also supports the passing of initial parameters. There are many advantages. This pattern is one of the most widely used and most ECMAScript methods in the creation of custom objects.

  Dynamic Prototyping Mode

The dynamic prototyping pattern encapsulates all information in the constructor, and initializes the prototype in the constructor (only when the first object is instantiated), which can be chosen to initialize the prototype by determining whether the method is valid.

function Blog (name, url) {
  this.name = name;
  This.url = URL;

  if (typeof this.alertinfo!= ' function ') {
    //This code only executes one
    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:***.com ');

You can see the above example only pop-up window, ' exe time ', that is, when the blog initialization, this does not need to initialize the prototype, the use of this pattern to create objects, can be regarded as a perfect of the blog2.

This post refers to the 3rd edition of JavaScript Advanced programming, but the language has been simplified and the example has been rewritten, if there is anything you do not understand, please leave a message, the author will update the blog.

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.