A deep analysis of JavaScript object-oriented and prototype function _javascript techniques

Source: Internet
Author: User

Object is a very important stem in JavaScript, and it is directly related to your basic understanding of the entire JavaScript system, and to be clear, JavaScript is a group of objects. Beep )。

Here are some common types of object creation patterns

Create using the New keyword

The most basic way to create an object is to say the same as most other languages: no object, you new one!

var GF = new Object (); Gf.name = "Tangwei"; Gf.bar = "C + +"; Gf.saywhat = function () {Console.log (this.name + "said:love you Forever");}

Create with literal volume

It seemed to be settled, but the geek of the House could not have liked 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, and then there was the definition of object literal:

var GF = {Name: "Tangwei", bar: "C + +", saywhat:function () {Console.log (this.name + "said:love you Forever");}

Factory mode

This is actually the most commonly used object definition in practice, but I want to have a lot of objects with similar attributes (it's exciting to think ...). ) What to do? that if a definition, will produce a lot of code, why not build a factory, batch production of our objects, so, JavaScript the world's first inflatable baby ... 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");

Constructors

The factory pattern solves the problem of creating multiple similar objects, but the problem is that they are all object-specific, how do you differentiate their object types? That's when we need to switch to another pattern, the constructor pattern:

function Gf (name,bar) {this.name = name; this.bar = bar; this.saywhat = function () {alert (this.name + "Said:love you Forev Er "); } var GF1 = new Gf ("Vivian", "F"); var gf2 = new Gf ("Vivian2", "F");

Here we replace the CREATEGF in the previous example with a constructor that starts with a capital letter, noting that the first letter of the contract constructor is capitalized. Here we create a new object and then assign the constructor's scope 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:

Console.log (Gf1.saywhat = = Gf2.saywhat); False

Calling the same method, but declaring different instances, is a waste of resources. We can optimize it. Place the Saywhat function outside the constructor declaration:

function Gf (name,bar) {this.name = name; this.bar = bar; this.saywhat = saywhat} function saywhat () {alert (this.name + "s Aid:love you Forever "); }

This solves the problem that multiple instances define the same method instance multiple times, but the new problem comes again, the saywhat we define is a global scope method, but this method is not directly invoked, which is a bit contradictory. How to more elegantly define an object with a certain encapsulation? Let's take a look at the JavaScript prototype object pattern.

Prototype Object pattern

Understanding the Prototype object

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

In prototype mode, you do not have to define an instance property in the constructor to give the property information directly 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 properties and methods of new objects here are shared by all instances, in other words GF1 and GF2 are accessing the same properties and methods. In addition to the attributes we give to the prototype object, there are some built-in attributes, all of which have a constructor attribute, which is a pointer to a function containing the prototype property (dare not go around a bit!). )。 In a picture, let's take a clear look at the flow around the mouth:

All objects have a prototype object (prototype), and a constructor attribute in the prototype object points to a function that contains the prototype property. GF's instance GF1 and GF2 both contain an internal attribute pointing to a prototype object (represented 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 look for the prototype object.

Using a prototype object

In the previous example, we noticed that when adding attributes to a prototype object, we needed to add gf.prototype to each, and this work was repeated, and in the creation pattern of the object above, we knew we could create an object in literal form, and here we could improve:

function Gf () {} Gf.prototype = {name: "Vivian", bar: "C + +", saywhat:function () {alert (this.name + "Said:love you fore Ver "); } }

Here's a place to pay special attention to, the constructor property no longer points to 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:

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 needs for constructor, we can also explicitly specify the constructor attribute of the following gf.prototype:

Gf.prototype = {CONSTRUCTOR:GF, name: "Vivian", bar: "C + +", saywhat:function () {alert (this.name + "said:love you f") Orever "); } var GF1 = new Gf (); Console.log (gf1.constructor = Gf);//true

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

Constructors and prototype combination patterns

In actual 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.

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, we define the respective property values of the objects in the constructor, define the constructor property and the Saywhat function in the prototype object so that there is no effect between the GF1 and the GF2 properties. This model is also the most commonly used object definition method in actual development, including many JS libraries (bootstrap, etc.) by default mode.

The above is a small set to introduce the JavaScript object-oriented and prototype functions, I hope to help.

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.