Simple analysis of JS prototype Object & Instance Object & Constructor (GO)

Source: Internet
Author: User

Analysis of the relationship between prototype object, instance object and constructor function

Original address: JS Object-oriented-prototype object, instance object, constructor relationship (http://blog.csdn.net/u014205965/article/details/45798861)

Because the object on the root has a prototype property, and all the objects in JS inherit from object, so all the objects in JS have a prototype attribute, and in JS the function is the object, So each function in JS also has a prototype attribute.

For example: function person () {...} and function Dog () {...}

And each prototype property gets a constructor property

The constructor property has an implied pointer to the function where the prototype property resides.

This shows that when the Person.prototype.constructor is popped with the alert function, the result is

Function person{....}

When an object instance is created through new person (), the instance contains an implied pointer to the Person.prototype

In conjunction with the previous example, the relationship between the constructor, the instance object, and the prototype object is illustrated by a diagram.

Each instance of person contains a stealth pointer to Person.prototype, in other words, they are not directly related to the constructor function.

You can use isPrototypeOf () to determine whether an instance points to a prototype object, or whether an instance originates from a prototype object.

Alert (Person.prototype.isPrototypeof (p1)) returns True, indicating that P1 points to Person.prototype,

Person.prototype is the prototype object of the instance P1.

Deep understanding of the relationship between prototype objects, instance objects, and constructor functions

Original: In-depth understanding of JavaScript constructors and prototype objects (http://www.jb51.net/article/55539.htm)

Object, which is a very important stem in JavaScript, is a good understanding of how it is directly related to your basic understanding of the entire JavaScript system, which is, in plain parlance, a group of objects. Beep )。

Several common types of object creation patterns

Create with the New keyword
The most basic way to create objects is to say the same as most other languages: no object, you new one!

1 var New Object (); 2 gf.name = "Tangwei"; 3 Gf.bar = "C + +"; 4 function () {5     console.log (this. Name + "Said:love-Forever"); 6 }

Create with literal

This seems to be duly done, but how could the geek of the dwelling-house be fond of the way of defining variables of such complexity and low soil, as a scripting language that should have the same style as the other brothers, then there is the definition of the object literal:

1 var New Object (); 2 gf.name = "Tangwei"; 3 Gf.bar = "C + +"; 4 function () {5     console.log (this. Name + "Said:love-Forever"); 6 }

Factory mode

This is actually the most commonly used object definition in practice, but I want to have a lot of objects with similar properties (it's exciting to think ...). ) What to do? If one of the definitions, will generate a lot of code, why not build a factory, batch production of our objects, so, JavaScript World First Inflatable doll ... No, "Factory mode" was born!

1 functionCREATEGF (name, bar) {2   varo =NewObject ();3O.name =name;4O.bar =Bar;5O.saywhat =function() {6Alert This. Name + "Said:love You Forever");7   }8   returno;9 }Ten varGF1 = CREATEGF ("Bingbing", "D"); One varGF2 = CREATEGF ("Mimi", "a");

constructor function

Factory mode solves the problem of creating multiple similar objects, but again, these objects are all object, how to distinguish their object specific type? At this point we need to switch to another mode, the constructor mode:

1 functionGf (name,bar) {2    This. Name =name;3    This. Bar =Bar;4    This. Saywhat =function(){5Alert This. Name + "Said:love You Forever");6   }7 }8 varGF1 =NewGf ("Vivian", "F");9 varGF2 =NewGf ("Vivian2", "F");

Here we use a constructor that starts with a capital letter instead of the CREATEGF in the previous example, and notice that the first letter of the constructor is capitalized by convention. Here we create a new object and then assign the scope of the constructor to the new object, calling the method in the constructor.

There seems to be nothing wrong with the way above, but we can see that the Saywhat method in the constructor called in two instances is not the same function instance:

// false

Invoking the same method, but declaring a different instance, is a waste of resources. We can optimize it. Put the Saywhat function outside the constructor declaration:

1 function Gf (name,bar) {2   this. Name = name; 3   this. Bar = bar; 4   this. saywhat = saywhat5}6function  saywhat ( {7   alert (this. Name + "Said:love Forever"); 8 }

This solves the problem that multiple instances define the same method instance several times, but the new problem comes again, and the saywhat we define is a global scope method, but this method is not directly called, which is a bit contradictory. How do you define an object with a certain encapsulation in a more elegant way? Let's look at the JavaScript prototype object pattern.

Prototype Object pattern

Understanding prototype Objects
When we create a function, the function has a prototype property that points to the prototype object of the function created by the constructor. The popular point is that the prototype object is an object in memory that provides shared properties and methods for other objects.

In prototype mode, you can assign attribute information directly to a prototype object without having to define the instance properties in the constructor:

1 functionGf () {2Gf.prototype.name = "Vivian";3Gf.prototype.bar = "C + +";4Gf.prototype.sayWhat =function(){5Alert This. Name + "Said:love You Forever");6   }7 }8 varGF1 =NewGf ();9 gf1.saywhat ();Ten varGF2 =NewGf ();

Unlike constructors, the properties and methods of new objects here are shared by all instances, in other words GF1 and GF2 access the same properties and methods. In addition to the attributes we give to the prototype object, there are some built-in properties, all of which have a constructor property, which is a pointer to the prototype property function (dare to go around a bit!). )。 Let's get a clear picture of the flow of this wrap:

All objects have a prototype object (prototype), and a constructor property in the prototype object points to the function that contains the prototype property. GF Instances GF1 and Gf2 both contain an intrinsic property pointing to the prototype object (shown in the Firefox browser as a private property proto), and when we access a property in an object, we first ask if there is a property in the instance object, and if not, continue to find the prototype object.

Working with prototype objects
In the previous example, we noticed that when adding properties to a prototype object, it was necessary to add gf.prototype to each, which was very repetitive, and in the creation pattern of the object above, we knew we could create an object in the form of a literal, and here we can improve:

1 function Gf () {} 2 gf.prototype = {3   name: "Vivian",4   bar: "C + +", 5   function () {6     alert (this. Name + "Said:love Forever"); 7   }8 }

Here's a place to pay special attention, the constructor property no longer points to the object GF, because each time a function is defined, a prototype object is created for it, and the object automatically acquires a new constructor property. This place we use Gf.prototype essentially overwrite the original prototype object, so constructor also becomes the constructor attribute of the new object, no longer pointing to GF, but object:

1 var New Gf (); 2 console.log (gf1.constructor = = Gf); // false 3 console.log (gf1.constructor = = Object)//true

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

1Gf.prototype = {2 CONSTRUCTOR:GF,3Name: "Vivian",4Bar: "C + +",5Saywhat:function() {6Alert This. Name + "Said:love You Forever");7   }8 }9 varGF1 =NewGf ();TenConsole.log (Gf1.constructor = = Gf);//true

Through a preliminary understanding of the prototype object pattern, we find that all the instance objects share the same attributes, which is the basic feature of the prototype pattern, but often for developers this is a "double-edged sword", in actual development, we hope that the instance should have its own properties, This is also the main reason why few people use the prototype mode alone in actual development.

Constructor and prototype combination modes

In real-world development, we can use constructors to define properties of objects, use prototypes to define shared properties and methods, so that we can pass different parameters to create different objects, while having shared methods and properties.

1 functionGf (name,bar) {2    This. Name =name;3    This. Bar =Bar;4 }5Gf.prototype = {6 CONSTRUCTOR:GF,7Saywhat:function() {8Alert This. Name + "Said:love You Forever");9   }Ten } One varGF1 =NewGf ("Vivian", "F"); A varGF2 =NewGf ("Vivian1", "C");

In this example, we define the property values of the objects in the constructor, define the constructor attribute and the Saywhat function in the prototype object, so that there is no effect between the GF1 and the GF2 attribute. This mode is also the most commonly used method of object definition in actual development, including many JS libraries (bootstrap, etc.) the default adopted mode.

Simple analysis of JS prototype Object & Instance Object & Constructor (GO)

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.