JavaScript prototype object prototype

Source: Internet
Author: User
Tags hasownproperty

"Each function we create has a prototype (prototype) attribute, which is a pointer to an object, and the purpose of this object is to include properties and methods that can be shared by all instances of a particular type. ”

The reference type has the prototype property, which contains:

1.object2.function3.array4.date5.string6.regexp such as:
1 var fn=New String ("text"); 2 string.prototype.value= "Val"; 3 Console.log (fn.value);  Val

1 functionPerson (name) {2      This. name=name;3 }4Person.prototype.getName =function() { 5         return  This. Name;6     }; 7 varP1 =NewPerson ("Evan");8 9Console.log (P1.name);//EvanTenConsole.log (P1.getname ());//Evan

This prototype property is also equivalent to dynamically adding properties or methods

Let's look at a more detailed example:

1 functionPerson () {2 }3Person.prototype.name = "Nicholas";4Person.prototype.age = 29;5Person.prototype.job = "Software Engineer";6Person.prototype.sayName =function(){7Console.log ( This. Name)8 };9 varPerson1 =NewPerson ();Ten varPerson2 =NewPerson (); OnePerson2.sayname ();//Nicholas AConsole.log (Person1.sayname = = Person2.sayname);//true

A picture looks at the relationship of each object:

There is only one prototype attribute in person, pointing to the prototype object. In the prototype object, constructor points to its constructor (its source), and other prototype property methods.

Person.prototype is the prototype isprototypeof determine whether they have a relationship, object.getprototypeof get the prototype value

1   // Object {name: "Nicholas", age:29, Job: "Software Engineer"}  (Prototype object)2   // true; 3   // Nicholas; 4   // true

If you change the example slightly, add the name attribute to the instantiated Person1 and assign the value: Name:me

1 ↑2Person1.name = "Me";3  4 //find it in the instance first, no more in the prototype.5Console.log (person1.name);//me
Console.log (Person1.constructor = = person);//true6 7 //use Hasownprototy () to detect if the property is in the instance, false to indicate that the attribute is from the prototype8Console.log (Person1.hasownproperty ("name"));//true9Console.log (Person2.hasownproperty ("name"));//falseTen One //use an in to detect if there is a secondary attribute, whether in an instance or in a prototype AConsole.log ("name"inchPerson1);//true -Console.log ("name"inchPerson2);//true

Person1 and Person2 are instantiated person, can also access the person's prototype object, with the pointer [[Prototype]] to implement, we can not manipulate [[Prototype]], but there is another __proto__ to access.

Next example.

1 ↑ 2  Console.log (Person1.prototype); // undefined 3  Console.log (Person.prototype); // Object {name: "Nicholas", age:29, Job: "Software Engineer"} 4  Console.log (person1.__proto__); // Object {name: "Nicholas", age:29, Job: "Software Engineer"} 5  Console.log (person.__proto__); // function () {}

Instantiating an object invokes a prototype object, which is a __proto__ pointer, not a prototype property. It does not have a prototype object in itself, it is a prototype object to call the constructor.

When the constructor (person) invokes the __proto__ pointer, it returns itself.

The difference between __proto__ and prototype: (IE does not support __proto__)

__PROTO__: Reference to the internal prototype of the object.

Prototype: Returns the prototype of the object.

When we access the properties of an object, if the object does not exist inside this property, then he will go to __proto__ to find this attribute, this __proto__ will have their own __proto__, so has been looking down, that is what we usually say the prototype chain the concept. So __proto__ is a bridge between the various objects.

1  var function  () { }; 2  var New Person (); 3  Alert (p.__proto__ = = = Person.prototype);  True

This example is easy to understand, the source of instance p is the person's prototype

Look at a complex example:

1   varperson =function () { };2Person.prototype.Say =function () {3Alert ("Person say");4     }5Person.prototype.Salary = 50000;6  7   varProgrammer =function () { };8Programmer.prototype =NewPerson ();9Programmer.prototype.WriteCode =function () {TenAlert ("Programmer writes Code"); One   }; AProgrammer.prototype.Salary = 500; -  -   varp =NewProgrammer (); the P.say (); -  P.writecode (); -alert (p.salary);

Let's do this derivation:

var p=new Programmer () can be obtained p.__proto__=programmer.prototype;

And on top we specify programmer.prototype=new person (); Let's split this up, Var p1=new person (); PROGRAMMER.PROTOTYPE=P1; then:

P1.__proto__=person.prototype;

Programmer.prototype.__proto__=person.prototype;

Get P.__proto__=programmer.prototype on top of the above. Can get p.__proto__.__proto__=person.prototype.

Well, after figuring it out, let's look at the results above, P.say (). Because P does not say this property, so go to p.__proto__, that is, Programmer.prototype, that is, p1 to find, because there is no P1 say, then go to p.__proto__.__proto__, that is Person.prototype to find, so found the alert ("Person say") method.

(Reference: http://rockyuse.iteye.com/blog/1426510)

1 var student = {name: ' Aaron '2 console.log (student.__proto__);//object {}

All objects in JS are inherited from the object, so the source here is object {}

About inheritance

1  functionAnimal () {}2animal.prototype.say=function(){return"WWW"};3  functionPerson () {}4person.prototype.say=function(){return"Hello"};5Person.prototype =NewAnimal ();6 varP2 =NewPerson ();7P2.say (); Www

Inheritance is implemented when an object's prototype points to another object. As in the example, person inherits animal

At this point, be aware that both the parent class and the subclass have their own prototype. After inheritance, the instance object constructor of the subclass points to the parent class. As follows

1 ↑ 2 Console.log (p2.constructor); // function Animal () {} 3 console.log (object.getprototypeof (Person.prototype). constructor); // function Animal () {}

This is normal, it should be so. But sometimes it's not the result we want. As the example above, although inherits the parent class, but P2.say () I want it to output the result of the subclass, how to do it?

Simply rewrite after integration to

1   functionAnimal () {}2animal.prototype.say=function(){return"WWW"};3   functionPerson () {}4person.prototype.say=function(){return"Hello"};5Person.prototype =NewAnimal ();6person.prototype.say=function(){return"I am People"}//Override the parent class function here7   varP2 =NewPerson ();8 9P2.say ();//I am people

Problems with reference types:

1 functionSupertype () { This. color = ["Red", "Blue", "green"]}2 functionsubtype () {3 }4Subtype.prototype=Newsupertype ();5 vars1=Newsubtype ();6S1.color.push ("Black");7Console.log (S1.color);//["Red", "Blue", "green", "black"]8 varS2=Newsubtype ();9Console.log (S2.color);//["Red", "Blue", "green", "black"]

S1 and S2 are subclasses of the instantiation, S1 inherit the parent class's Color property to add, supposedly can only S1 themselves Add. The result is that the properties of other objects instantiated by the class are changed.

Subtype.prototype=new supertype (); the equivalent: A subclass is an instance of the parent class, and the subclass has its own color property. However, when instantiating subclasses, S1 and S2 share the Color property, which causes the changes to be changed together.

It must be unreasonable. Change

1function Supertype () { This. color = ["Red", "Blue", "green"]}2 functionsubtype () {3Supertype.call ( This);4 }5Subtype.prototype=Newsupertype ();6 vars1=Newsubtype ();7S1.color.push ("Black");8 Console.log (ss.color);//["Red", "Blue", "green", "black"]9 varS2=Newsubtype ();TenConsole.log (S2.color); ["Red", "Blue", "green"]

The call () function, when closed, binds a function to an object. In this case, it is equivalent to taking the parent function, calling it in its own scope, borrowing the constructor, or overriding the parent class.

So every time you instantiate a subclass, you call a subclass of the overridden function, make one assignment, and each instance has its own color property. Non-interference.

This article is a summary of learning, if there is an incorrect, to correct.

JavaScript prototype object prototype

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.