Object-oriented =====> Engineering mode/constructor/prototype mode

Source: Internet
Author: User

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

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 the future and avoid tedious duplication of work. Next, we will explain the object-oriented implementation in JS.

Factory mode

Factory mode is a well-known design pattern in the field of software engineering, and because a class cannot be created in ECMAScript, a function encapsulation is used to create an object with a specific interface. The implementation method is very simple, that is, to create an object within the function, give the object properties 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 type of the object, because it is all object, unlike date, array, etc., so a constructor pattern occurs.

  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:

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, determines whether the blog is an instance of the blog, that is, to solve the Factory mode can not

This example differs from the factory model in that there are many differences in the careful child shoes except the function names:

The first letter of the function name is uppercase (although the standard does not strictly stipulate that uppercase is capitalized, but by convention, the initial letters of the constructor are capitalized
Create objects that are not displayed
Assigning properties and methods directly to the This object
No return statement
Create an object using new
Ability to recognize objects (this is where the constructor pattern is better than the factory pattern)

Although the constructor works well, it is not without 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 (perhaps some children's shoes have seen shortcomings, 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 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 to let the global scope some veritable, What's even more unacceptable is that many methods are defined in the global scope that are only used by 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, and the purpose of this object is to include 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 object instances share the properties and methods that 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,fr4blog2.alertinfo ();  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

Prototype mode is not without shortcomings, first of all, it omitted the constructor passed the initialization parameters of the link, the result all instances in the default to obtain the same property value, this is very inconvenient, but this is not the biggest problem of the prototype, the biggest problem of the prototype model is the nature of sharing caused by, 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.

  Mixed Mode (prototype Mode + constructor mode)

function Blog (name, URL, friend) {  this.name = name;  This.url = URL;  This.friend = friend;} Blog.prototype.alertInfo = function () {
This piece of code executes multiple times
Alert (' exe time ') 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

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 sharing the method, the maximum memory savings. In addition, this mode also supports passing the initial parameters. There are many advantages. This pattern is the most widely used and most recognized method of creating custom objects in ECMAScript.

  Dynamic Prototyping Mode

The dynamic prototype pattern encapsulates all information in the constructor, while initializing the prototype through the constructor (initializing the prototype only when the first object is instantiated), which can be chosen by determining 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 executes only 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 in the above example only pop-up window, ' exe time ', that is, when the blog initialization, so BLOG2 does not need to initialize the prototype, for using this mode to create objects, can be considered perfect.

Object-oriented =====> Engineering mode/constructor/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.