JavaScript prototype and prototype chain analysis

Source: Internet
Author: User

JavaScript does not have the concept of class, but almost everything is object-based, but also to achieve inheritance, which is the biggest difference between JS and other OOP language, which is the most difficult to understand JS. Let me say my personal understanding.

First of all, from the creation of the object, there are generally the following methods:

1. Create an object instance, and then add properties and methods to it.

var New  = ' mikej 'function() {  alert (this. name);}

2. You can also write this:

1 var parson = {2   name: ' Mikej ',3   function() { 4     Alert (this. Name); 5   }6 }

3. The two methods of creating objects are simple, but flawed, creating a large number of duplicate code when objects are created using the same schema. Then there is the factory model:

1 functionCreateperson (name) {2   varp =NewObject ();3P.name=name;4P.sayname =function(){5Alert This. Name);6   };7   returnp;8 }9 varP1 = Createperson (' Mikej '));Ten varP2 = Createperson (' Tom ');

This makes it possible to create objects indefinitely.

4. There is also a method, similar to the factory model, called the constructor mode:

1 functionPerson (name) {2    This. name=name3    This. Sayname =function(){4Alert This. Name);5   }6    This. Say =function(){7Alert (' Hi '));8   }9 }Ten varP1 =NewPerson (' Mikej '); One varP2 =NewPerson (' Tom ');

Here are a few areas to watch out for: Create objects that are not displayed, the function name person uses the uppercase letter P (which is required), p1, and P2 have a constructor (constructor) attribute that points to person. Both P1 and P2 are both instances of object and instances of person.

1 // true 2 instanceof // true 3 instanceof // true

5.11 Update: In a phper perspective, it is easy to think of the process of creating objects so that the person is a "class", then instantiate the new Person(‘mikej‘) class and pass in the parameters. But this is not actually the case, the process should be created: first, create an empty object, then use the Apply method, the first argument is the empty object, the second argument is the context parameter, so that the this in person will point to this object, that is, p1.

1 var New Person (' mikej '); 2 // The above code is equivalent to 3 var p1 = {}; 4 person.apply (P1, [' Mikej ']);

The constructor pattern looks good, but one drawback is that it wastes memory, and then the example

// false

To avoid this flaw, but using prototype mode to create objects, each object in JS has a prototype attribute to point to another object, and all properties and methods of that object are inherited by the instance of the constructor and are shared, which means that we can put the invariant properties and methods, Defined on the prototype object.

functionPerson (name) {this.name=name;}//Person 's prototype object Person.prototype={say:function() {alert ('Hi'); }, Sayname:function() {alert (this.name); }};var P1= New Person ("mikej ");var p2 = new Person ("Tom ");p1.sayname ();p 2.sayName ();//as you can see here, the method implements the shared alert (P1.say= = P2.say)//trueAlert (P1.sayname= = P2.sayname)//true

To extend the example above, use prototypes to implement inheritance.

function Person (name) { This. Name =name;} Person.prototype={say:function () {alert ('Hi'); }, Sayname:function () {alert ( This. Name); }};function Programmer () { This. Say =function () {alert ('im Programmer, my name is'+ This. Name); }}programmer.prototype=NewPerson ('Mikej');//Manually fix ConstructorsProgrammer.prototype.constructor =Programmer;varP1 =NewProgrammer (); Console.dir (Programmer.prototype.constructor);//ProgrammerConsole.dir (P1.constructor);//ProgrammerConsole.dir (p1);

Programmer's prototype points to an instance of person, all instances of programmer can inherit the prototype of person and person.

There will be a problem here.

The default prototype object has a constructor property, which points to its constructor. Each instance also has a constructor property, which invokes the constructor property of the prototype object by default.

Assuming noProgrammer.prototype = new Person(‘mikej‘);

Programmer.prototype.constructor is pointing to Programmer. The structure of the P1 also points to programmer

// true // true

But with this sentence Programmer.prototype = new Person(‘mikej‘); ,

The Programmer.prototype.constructor points to object, which is the construction of objects pointed to by Person.prototype. The p1.constructor also points to object. But P1 is obviously generated by the constructor programmer, which causes the confusion of inheritance, so we have to manually fix the constructor, which is the code below.

Programmer.prototype.constructor = Programmer;

OK, now let's take a look at the prototype chain:

Console.dir (p1);

The result of this code is

It can be seen that P1 is an example of programmer, programmer prototype is Person,person prototype is an object, and then the Internet is JS objects. This is the prototype chain, which means that the inheritance of JavaScript is based on the prototype chain.

JavaScript prototype and prototype chain analysis

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.