Deep understanding of javascript constructor and prototype object, and javascript Constructor

Source: Internet
Author: User

Deep understanding of javascript constructor and prototype object, and javascript Constructor

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(); = "tangwei"; = "c++";gf.sayWhat = function() {  console.log( + "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( + "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(); = name; = bar;  o.sayWhat = function() {    alert( + "said:love you forever");  }  return o;}var gf1 = createGf("bingbing","d");var gf2 = createGf("mimi","a");


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){ = name; = bar;  this.sayWhat = function(){    alert( + "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){ = name; = bar;  this.sayWhat = sayWhat}function sayWhat(){  alert( + "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(){ = "vivian"; = "c++";  Gf.prototype.sayWhat = function(){    alert( + "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( + "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);//falseconsole.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( + "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){ = name; = bar;}Gf.prototype = {  constructor : Gf,  sayWhat : function() {    alert( + "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.

Several minor issues with javascript constructors, prototypes, and instances

What you see is also a dumb's understanding about javascript. This blog series is very powerful and I personally admire it.

Enter the subject:
Alert (; // the pop-up 'dummy' motto is displayed because this attribute is not found in clone01, and the parent object of this object is found from the prototype chain, because

HumanCloning. prototype = {name: 'dummies '}
So the parent object is {name: 'dummies '}
Because the parent object has the name attribute, this attribute of the parent object is read.

Alert (clone01 instanceof HumanCloning); // 'false' is displayed'

It is because HumanCloning. prototype = {};
As a result, HumanCloning. prototype cannot be found on the prototype chain in clone01, so false is displayed.

Ps: instanceof the principle of checking whether object A is another object B is: Check whether the prototype of object B points to the object in the [[prototype] chain of object. If yes, true is returned. If not, false is returned. However, when prototype of object B is null, an error is returned (similar to a null pointer exception ). (Source: blog garden-the motto of dummies)

In javascript, for example, objprototypeconstructor points to an error, not to the constructor itself. What is the impact?

1. Only function objects have the prototype attribute.
2. Any object has a constructor.
3. prototype is not a function
4. The obj constructor is the object. constructor.
5. The prototype attribute of the function makes sense only when the function is used as the constructor to construct an object. The object to which it points stores the attributes inherited by the newly constructed object.
6. the constructor of all Function objects is a Function.
7. When a function is declared, the constructor attribute value of the prototype attribute of the function is the function's own
8. If you cannot understand it at, you can verify it.

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: 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.