Prototype parsing in JavaScript "recommended" _javascript tips

Source: Internet
Author: User
Tags hasownproperty

Recently in learning JavaScript, learning to JS Object-oriented prototype, a lot of sentiment. If there is a wrong place, I hope I can correct it.

JS as an object-oriented language, nature also has the concept of inheritance, but there is no class in JS concept, there is no similar to the extends in Java, so, I think the inheritance in JS mainly depends on the prototype in JS (chain).

So, what is a prototype? We know that the JS function is also an object, when we create a function, in fact, this function also defaults to have a property called prototype, this generic is called the prototype attribute, he is a pointer to the function of the prototype object, This prototype object has a default attribute called constructor, which points to a function that has a protptype.

function person () {}
    person.prototype={
//Constructor:person;
      First_Name: "Guo",
      hair_color: "Black", City
      : "Zhengzhou",
      act:function () {alert ("eatting");}
    ;

To take this as an example, we first created a function person, which, by default, has a property prototype that points to Person.propttype, which has a default attribute constructor (), Person.prototype.constructor--->person. (in fact, the default is to point to object, the following will be corrected)

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 point, we need to know that the constructor in JS and function is the difference is this new keyword, the new operator is a function is a constructor. When we create an instance object of person to save it in Boy,girl, the two instance objects generate a default property called _proto_ (available [[prototype]] in ECMAScript5, which points to the prototype object of the constructor. That is, boy._proto_--->person.prototype (unrelated to the constructor). At this point, boy or girl can invoke the generic type in the prototype object by point, and you know that Boy,girl shares the generic of the prototype object. We can verify the above conclusion by isprotptypeof () or object.getprototypeof () (The return value of this function is the prototype object, which is the _proto_ value).

Alert (Person.prototype.isPrototypeOf (boy)); True 
alert (object.getprototypeof (Boy). first_name);  "Guo" 

At this point, we can do further validation, what happens if you create a property in the instance that has the same name as the stereotype object attribute?

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 

This shows that the name of the name declared in the instance will mask the properties in the prototype object, but it will not affect the prototype object's generic type (Object.getprototypeof (boy). Hair_color==black), Also does not have an impact on other instance objects of the shared prototype object generic (Girl.hair_color==black). At the same time, you can use the delete operator to remove the properties of an instance object declaration to undo the masking effect. We can use hasOwnProperty () to verify whether a generic is present in the instance (true) or in the prototype object (FALSE).

Alert (Boy.hasownproperty ("Hair_color")); True

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

var key=object.keys (person.prototype); 
alert (key); 

Learning these, we will find that using the above method to declare a prototype object will have a problem, constructor no longer point to person, which we say the prototype object constructor attribute by default to the function containing the prototype property of the opposite, This is because each creation of a function automatically creates a prototype object, which creates the constructor by default. So, our essence here is to override the default prototype, so the new consrtuctor becomes the object function and no longer points to the person function. If constructor is really important, then you need to write Constructor:person.

After that, we need to know the dynamics of the prototype and change the attributes in the prototype object to the instance, regardless of whether the instance was created before or after the generic 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 above code is visible, even if the modification of a prototype object property occurs after the instance was created, the boy instance shares the Person.prototype.hobby.

However, this situation only occurs in the prototype object generic modification, when the prototype object properties are fully overridden, the creation of the instance must be placed behind the stereotype object property overrides, otherwise there will be an error.

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 "shielding" issue, we learned earlier that creating an instance object (with the same name as a property in a prototype object) masks the properties of the prototype object, but does not affect other instance objects. Here's an error, which applies only to basic data types, and when the value of a property refers to a type, a big problem arises, looking at 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

As you can see, the above sentence does not apply because friends is present in the prototype object, not in the boy, so his modification will affect the environment. (We can use boy.frindes=[] to create a boy instance's properties) then we need to introduce a combination of constructor and prototype patterns.

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 pattern is the most widely used and most recognized method of creating custom types at present ECMAScript, and can even be used as a default mode.

But for programmers who are engaged in other object-oriented languages, this pattern seems bizarre, and in order to encapsulate all the information into a constructor, the dynamic prototype pattern appears. Dynamic mode mainly uses an if statement to determine whether a prototype object needs to be initialized to achieve the goal of saving resources.

There is also a secure construction pattern to accommodate the absence of shared properties and the use of this.

The above JavaScript in the prototype analysis "recommendation" is small to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud habitat community.

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.