Prototype parsing in javaScript [recommended] and javascript prototype Parsing

Source: Internet
Author: User
Tags hasownproperty

Prototype parsing in javaScript [recommended] and javascript prototype Parsing

I recently learned a lot about javaScript and javaScript object-oriented prototype. If something is wrong, correct it.

As an object-oriented language, js naturally inherits this concept, but js does not have the class concept, so it does not have extends similar to java, I think the inheritance in js mainly depends on the prototype (chain) in js ).

So what is the prototype? We know that functions in js are also an object. When we create a function, this function actually has a property named prototype by default, which is called a prototype attribute, he is a pointer pointing to the prototype object of this function. The prototype object has a default attribute called constructor, which points to a function with a protptype.

function Person(){}    Person.prototype={     // constructor:Person;      first_name:"guo",      hair_color:"black",      city:"zhengzhou",      act:function(){alert("eatting");}    };

In this example, we first create a function Person, which has a default prototype attribute pointing to Person. the propttype object, which has a default attribute constructor (), Person. prototype. constructor ---> Person. (In fact, the default value here is to point to the Object, which will be corrected later)

What happens when we create an instance through the constructor?

function Person(){}   Person.prototype={     first_name:"guo",     hair_color:"black",     city:"zhengzhou",     act:function(){alert("eatting");}   };   var boy=new Person();   var girl=new Person(); 

At this moment, we need to know that the difference between constructors and functions in js is the new Keyword. A function using the new operator is a constructor. When we create a Person Instance Object and save it in boy or girl, the two instance objects generate a default attribute named _ proto _ ([prototype] can be used in ECMAScript5), which points to the prototype object of the constructor, that is, boy. _ proto _ ---> Person. prototype (unrelated to the constructor ). In this case, the boy or girl can call the type in the prototype object by clicking. You need to know that the boy and girl share the prototype. We can use isProtptypeOf () or object. getPrototypeOf () (the return value of this function is the prototype object, that is, the value of _ proto _) to verify the above conclusion.

alert(Person.prototype.isPrototypeOf(boy)); //true alert(Object.getPrototypeOf(boy).first_name);  //"guo" 

In this case, we can perform further verification. What if a property with the same name as the property of the prototype object is created in the instance?

var boy=new Person(); var girl=new Person(); boy.hair_color="red";  alert(boy.hair_color);  //red alert(girl.hair_color); //black alert(Object.getPrototypeOf(boy).hair_color);  //black 

It can be seen that the duplicate attribute declared in the instance will block the attributes in the prototype Object, but it will only be overwritten without affecting the prototype (Object. getPrototypeOf (boy ). hair_color = black) does not affect other instance objects that share the prototype (girl. hair_color = black ). At the same time, you can use the delete operator to delete the attribute declared by the instance object to cancel the blocking effect. We can use hasOwnProperty () to verify whether a prototype exists in an instance (true) or a prototype object (false ).

alert(boy.hasOwnProperty("hair_color")); //true

You can use Object. keys () to enumerate attributes.

var key=Object.keys(Person.prototype); alert(key); 

After learning this, we will find that there will be a problem in declaring the prototype object using the above method, and the constructor will no longer point to the Person, this is different from the constructor attribute of the prototype object. By default, the constructor attribute points to a function with the prototype attribute. This is because a prototype object is automatically created every time a function is created, and a constructor is created by default. Therefore, our essence here is to rewrite the default prototype, so the new consrtuctor is also changed to the Object function, instead of the Person function. If constructor is really important, you need to write constructor: Person.

After that, we need to know the dynamic nature of the prototype. Changing the attributes of the prototype object will reflect to the instance, regardless of whether the instance is created before or after the prototype change of the prototype object.

function Person(){} Person.prototype={   first_name:"guo",   hair_color:"black",   city:"zhengzhou",   act:function(){alert("eatting");} };  var boy=new Person(); Person.prototype.hobby="basketball"; var girl=new Person(); alert(boy.hobby); //basketball 

The code above shows that even if the modification to the properties of the prototype object happens after the instance is created, the boy instance shares the Person. prototype. holobby.

However, this happens only when the prototype object type is modified. When the prototype object attribute is completely overwritten, the instance creation must be placed after the prototype object attribute rewriting; otherwise, an error occurs.

function Person(){}     var girl=new Person();     Person.prototype={       first_name:"guo",       hair_color:"black",       city:"zhengzhou",       act:function(){alert("eatting");}     };      var boy=new Person();     Person.prototype.hobby="basketball";          alert(boy.hobby);  //basketball     alert(girl.first_name);  //undefined 

Back to the "blocking" issue, we previously learned that the attributes of the created instance object (with the same name as a property in the prototype object) will shield this attribute of the prototype object, but it does not affect other instance objects. Here is an error, which only applies to the basic data type. When the attribute value references the type, a major problem occurs. See the following code.

function Person(){}        Person.prototype={      first_name:"guo",      hair_color:"black",      friends:["Nick","John"],      city:"zhengzhou",      act:function(){alert("eatting");}    };    var boy=new Person();    boy.friends.push("Mike");    var girl=new Person();    alert(boy.friends);  //Nick,John,Mike    alert(girl.friends); //Nick,John,MIke

It can be seen that the above sentence is not applicable because friends exists in the prototype object rather than the boy object, so his modifications will affect the environment. (We can use boy. frindes = [] to create a boy instance attribute.) Then we need to introduce the constructor mode and prototype mode.

function Person(hair_color,city){              this.hair_color=hair_color;       this.city=city;       this.friends=["John","Nick"];     }     Person.prototype={       constructor:Person,       first_name:"guo",       act:function() {                  alert("eatting");       }     };     var boy=new Person("black","zhengzhou");     var girl=new Person("red","shenyang");     boy.friends.push("Nick");     alert(girl.friends);     alert(boy.friends); 

This mode is currently the most widely used in ECMAScript. It recognizes the highest method for creating custom types and can even be used as a default mode.

However, for programmers engaged in other object-oriented languages, this pattern is very strange. To encapsulate all the information into constructors, the dynamic prototype pattern has emerged. The dynamic mode mainly uses an if statement to determine whether to initialize the prototype object to save resources.

In addition, there is a secure construction mode to adapt to the absence of shared attributes and the absence of this.

The prototype analysis [recommendation] in the above javaScript is all the content shared by Alibaba Cloud xiaobian. I hope you can give us a reference and support the help house.

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.