In-depth analysis of JavaScript object-oriented and prototype functions, and javascript object-oriented

Source: Internet
Author: User

In-depth analysis of JavaScript object-oriented and prototype functions, and javascript object-oriented

Objects are very important in javascript. Whether you fully understand them is directly related to your basic understanding of the entire javascript system. To put it bluntly, javascript is a group of objects .. (Beep !).

The following describes several common object creation modes.

Create with the new Keyword

The most basic object creation method is the same as that in most other languages: no object. You are new!

var gf = new Object(); gf.name = "tangwei"; gf.bar = "c++"; gf.sayWhat = function() { console.log(this.name + "said:love you forever"); }

Create with literal

This seems to be appropriate, but can the static geek like the complicated and low-Earth way to define variables? As a scripting language, it should be the same as those of other geeks, the definition of the object literal volume is as follows:

var gf = { name : "tangwei", bar : "c++", sayWhat : function() { console.log(this.name + "said:love you forever"); } }

Factory Model

In fact, this is the most common object definition method in practice, but I want to have a lot of objects with similar attributes (think about it as exciting ...) What should we do? If we define them one by one, a lot of code will be generated. Why not create a factory to produce our objects in batch? So, the first inflatable doll in the javascript world... No, the "factory model" was born!

function createGf(name, bar) { var o = new Object(); o.name = name; o.bar = bar; o.sayWhat = function() { alert(this.name + "said:love you forever"); } return o; } var gf1 = createGf("bingbing","d"); var gf2 = createGf("mimi","a");

Constructor

The factory mode solves the problem of creating multiple similar objects, but the problem arises again. These objects are all rounded up. How can we differentiate the specific types of their objects? At this time, we need to switch to another mode, the constructor mode:

function Gf(name,bar){ this.name = name; this.bar = bar; this.sayWhat = function(){ alert(this.name + "said:love you forever"); } } var gf1 = new Gf("vivian","f"); var gf2 = new Gf("vivian2","f");

Here, we use a constructor starting with an upper-case letter to replace creatgf in the above example. Note that the first letter of the constructor should be capitalized according to the Conventions. Here we create a new object, assign the scope of the constructor to the new object, and call the methods in the constructor.

The above method does not seem to be inappropriate, but we can find that the sayWhat method in the constructor called in the two instances is not the same Function instance:

console.log(gf1.sayWhat == gf2.sayWhat); //false

It is a waste of resources to call the same method but declare different instances. We can optimize the sayWhat function and put it out of the constructor to declare it:

function Gf(name,bar){ this.name = name; this.bar = bar; this.sayWhat = sayWhat } function sayWhat(){ alert(this.name + "said:love you forever"); }

This solves the problem of multiple instances defining the same Method Instance multiple times, but the new problem arises. The sayWhat we define is a global scope method, however, this method cannot be called directly, which is a bit contradictory. How can we more elegantly define an object with certain encapsulation? Let's take a look at the javascript prototype object mode.

Prototype Object Mode

Understanding prototype objects

When we create a function, the function will have a prototype attribute pointing to the prototype object of the function created by the constructor. In layman's terms, a prototype object is an object in memory that provides shared attributes and methods for other objects.

In the prototype mode, you do not need to define instance attributes in the constructor. You can directly assign the attribute information to the prototype object:

function Gf(){ Gf.prototype.name = "vivian"; Gf.prototype.bar = "c++"; Gf.prototype.sayWhat = function(){ alert(this.name + "said:love you forever"); } } var gf1 = new Gf(); gf1.sayWhat(); var gf2 = new Gf();

Unlike constructors, the attributes and methods of the new object can be shared by all instances. In other words, gf1 and gf2 access the same attributes and methods. In addition to the attributes assigned to the prototype object, there are also some built-in attributes. All prototype objects have a constructor attribute, this property is a pointer to a function that contains the prototype attribute (dare not go around again !). Through a picture, we can clearly understand the detour process:

All objects have a prototype. The prototype object has a constructor attribute pointing to a function containing the prototype attribute, both gf1 and gf2 instances of Gf contain an internal property pointing to the prototype object (expressed as a private property proto in firefox). When we access the property of an object, first, you are asked if this attribute exists in the instance object. If not, you can continue searching for the prototype object.

Use a prototype object

In the previous example, we noticed that when adding attributes to the prototype object, Gf needs to be added for each object. prototype, which is repeated. In the above object creation mode, we know that we can create an object in the form of a literal. Here we can also improve it:

function Gf(){} Gf.prototype = { name : "vivian", bar : "c++", sayWhat : function(){ alert(this.name + "said:love you forever"); } }

Note that the constructor attribute no longer points to the object Gf, because each function is defined to create a prototype object for it at the same time, this object will also automatically obtain a new constructor attribute, where we use Gf. prototype essentially overwrites the original prototype Object, so the constructor becomes the constructor attribute of the new Object, instead of pointing to Gf, but the Object:

var gf1 = new Gf(); console.log(gf1.constructor == Gf);//false console.log(gf1.constructor == Object)//true

In general, this subtle change will not affect us, but if you have special requirements for constructor, we can also explicitly specify Gf. constructor attribute of prototype:

Gf.prototype = { constructor : Gf, name : "vivian", bar : "c++", sayWhat : function() { alert(this.name + "said:love you forever"); } } var gf1 = new Gf(); console.log(gf1.constructor == Gf);//true

Through a preliminary understanding of the prototype object model, we found that all instance objects share the same property, which is the basic feature of the prototype model, but it is often a double-edged sword for developers ", in actual development, the desired instance should have its own attributes, which is also the main reason why few people use the prototype independently in actual development.

Constructor and prototype combination modes

In actual development, we can use constructors to define object attributes and prototype to define shared attributes and methods, in this way, we can pass different parameters to create different objects and share methods and attributes.

function Gf(name,bar){ this.name = name; this.bar = bar; } Gf.prototype = { constructor : Gf, sayWhat : function() { alert(this.name + "said:love you forever"); } } var gf1 = new Gf("vivian", "f"); var gf2 = new Gf("vivian1", "c");

In this example, the constructor and sayWhat functions are defined in the constructor of the prototype, in this way, the gf1 and gf2 attributes will not be affected. This mode is also the most common object definition method in actual development, including the default mode used by many JS libraries (such as bootstrap.

The above is a small part of the JavaScript object-oriented and prototype functions, I hope to help you.

Articles you may be interested in:
  • Js object-oriented methods of Common Object creation (factory mode, constructor mode, and prototype mode)
  • JS object-oriented basic explanation (factory mode, constructor mode, prototype mode, hybrid mode, dynamic prototype mode)
  • Object-oriented Javascript 2 (interface implementation)
  • JavaScript Object-Oriented Programming three prototype mode (I)
  • Introduction to Javascript Object-Oriented Programming
  • Js object-oriented design: {} Good or function () {} Good (constructor)
  • ExtJS4 componentized programming, dynamic loading, object-oriented, Direct
  • Deep understanding of javascript constructors and prototype objects
  • Basic explanation of JavaScript inheritance (prototype chain, borrow constructor, hybrid mode, original type inheritance, parasitic inheritance, and parasitic combined inheritance)
  • Constructors + prototype pattern construct js custom objects (most common)
  • Javascript-based constructor and prototype, and Dynamic Prototype
  • View the performance of js Regular Expressions by using trim prototype functions

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.