JavaScript prototype chain principle detailed _javascript skill

Source: Internet
Author: User
Tags hasownproperty

The principle of JavaScript prototype chain is analyzed in this paper. Share to everyone for your reference, specific as follows:

First, JavaScript prototype chain

The concept of prototype chain is described in ECMAScript, and the prototype chain is used as the main method to implement inheritance. The basic idea is to make a reference type inherit the properties and methods of another reference type using the prototype. In JavaScript, the __proto__ attribute is used to represent the prototype chain of an object. When you look up an object's properties, JavaScript traverses the prototype chain up until it finds the property of the given name!

For example, now you have the following code:

Extend object class, add clone and Extend methods

/* Extend Object class, add Clone,js method to implement cloning
/* Object.prototype.Clone = function () {
  var objclone;
  if (This.constructor = = Object) {
    objclone = new This.constructor (); 
  } else{
    objclone = new This.constructor (this.valueof ()); 
  }
  for (var key in this) {
    if (Objclone[key]!= This[key]) { 
      if (typeof (This[key)) = = ' object ') { 
        Objclone[key] = This[key]. Clone ();
      } else{
        Objclone[key] = This[key];
      }
    }
  objclone.tostring = this.tostring;
  objclone.valueof = this.valueof;
  return objclone; 
}
/* Extend the object class, add Extend method to implement JS inheritance, the target object will have all the properties and methods of the source object/
Object.prototype.Extend = function (Objdestination, Objsource) {for
  (var key in Objsource) {
    if (Objsource.hasownproperty (key) && objdestination[key] = = Undefined) {
      Objdestination[key] = Objsource[key];
    }
  return objdestination;
}

Defining the Person class

/* Define a person class *
 /function person (_name,_age) {
   this.name = _name;
   This.age = _age;
}

In JavaScript, the object class is the parent of all classes, so the person class inherits from the object class, inheriting all public and public methods of the object class, including the newly added clone and extend method of the object class

You can use the following code to prove that the person class does inherit the object class

document.write ("<pre>");
var p = new Person ("aloof wolf", 24);//Create a man, name is aloof wolf
var clonep = P.clone ();//p invoke the Clone method defined in the object class to clone itself, if you can get a CLONEP, That proves that the person class does inherit the object class, so it has the clone
Document.writeln ("P" is an object created in the form of a constructor using the person class, p.name = "+p.name+", P.age = "+p.age");
Document.writeln ("CLONEP is the object that P invokes the Clone method, Clonep.name =" +clonep.name+ ", Clonep.age =" +clonep.age ");
Document.writeln ("Clonep object and P object are two independent objects, the memory address of these two objects is certainly not equal, p = = CLONEP result is:" + (P = = CLONEP));
Clonep.name= "White tiger God Emperor";//Modify CLONEP name
Document.writeln ("CLONEP's name was modified, Clonep.name =" +clonep.name);
Document.writeln ("CLONEP name modified, but does not affect p,p.name =" +p.name);
document.write ("</pre>");

Run Result:

Then the person class inherits the object class by means of the divine horse, and is inherited using a prototype (Prototye):

/* Define a person class *
/function person (_name,_age) {
   this.name = _name;
   This.age = _age;
}
Person.prototype = new Object ()//Let the person class inherit the Object class

Because JavaScript rules that any class inherits from the object class, "Person.prototype = new Object ()//Let the person class inherit the object class " Even if we don't write, I guess the JavaScript engine will also automatically add this phrase, or use "person.prototype = Object.prototype;" This way, let the person class inherit the object class. "Person.prototype = new Object ();" In fact, this equates to the object being a prototype of person, which is equivalent to copying the object's properties and methods to the person.

Two, how the new operator works

Let's look at a piece of code like this:

Copy Code code as follows:
var p = new Person ("aloof wolf", 24);//Create a man, name is aloof Wolf

A very simple piece of code, let's see what this new one does. We can split the new process into three steps:

1.var p={}; Initializes an object p.

2. P.__proto__=person.prototype, set the __proto__ property of the object p to Person.prototype

3.person.call (P, "aloof Wolf", 24); Call constructor person to initialize p.

The key is the second step, and let's prove it:

var p = new Person ("aloof wolf", 24);//Create a man, name is aloof Wolf
alert ("p.__proto__ = = Person.prototype result is:" + (p.__proto__ = = Person.prototype));

The results of the operation under Firefox are:

This piece of code returns TRUE. Explain the correctness of our step 2.

Note: __proto__ This property is publicly accessible only in Firefox or in the Chrome browser, so other browsers based on the IE kernel will not return true.

So what's __proto__? Here simply to say. Each object initializes an attribute within it, which is __proto__, and when we access an object's properties, if it does not exist inside the object, then he goes to the __proto__ to find the attribute, and the __proto__ has its own __proto__, So keep looking, that is, we usually say the concept of the prototype chain.

According to the standard, __proto__ is not public, that is, a private property, under IE is unable to access the __proto__ properties, but the Firefox engine will expose him to become a public property, we can access and set.

Well, the concept is clear, let's take a look at the following code:

<script type= "Text/javascript" >
    var person = function () {};
    Person.prototype.Say = function () {
      alert (' Person Say ');
    }
    var p = new person ();
    P.say ();
</script>

The code is simple, so let's see why p can access the person's say.

First of all

Copy Code code as follows:
var p=new person ();

Can draw

Copy Code code as follows:
P.__proto__=person.prototype

So when we call P. Say (), first P has no Say this attribute, so he needs to go to his __proto__ to find, that is, person.prototype, and we have defined above

Person.prototype.say=function () {
    alert ("Person Say");


So, we found this method.

Next, let's look at a more complicated one.

<script type= "Text/javascript" >
    var person = function () {};
    Person.prototype.Say = function () {
      alert (' Person Say ');
    }
    Person.prototype.Salary = 50000;
    var programmer = function () {};
    Programmer.prototype = new Person ()//Let the programmer class inherit from the class
    Programmer.prototype.WriteCode = function () {
      alert (" Programmer writes Code ");
    Programmer.prototype.Salary = +;
    var p = new programmer ();
    P.say ();
    P.writecode ();
    alert (p.salary);
</script>

Let's do this derivation:

Copy Code code as follows:
var p=new programmer ();

Can draw

Copy Code code as follows:
P.__proto__=programmer.prototype;

And in the above we have specified

Copy Code code as follows:
Programmer.prototype=new person ();

Let's split up like this.

var p1=new person ();
PROGRAMMER.PROTOTYPE=P1;

So:

P1.__proto__=person.prototype;
Programmer.prototype.__proto__=person.prototype;

Based on the above obtained

Copy Code code as follows:
P.__proto__=programmer.prototype

can be obtained:

Copy Code code as follows:
P.__proto__.__proto__=person.prototype

Okay, well, we'll look at the results above, P.say (). Because P did not say this attribute, 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 Say method. This is the realization principle of the prototype chain.

The following code shows how the JS engine looks for attributes:

function GetProperty (obj, prop) {
  if (Obj.hasownproperty (prop)) return
    Obj[prop];
  else if (obj.__proto__!== null) return
    GetProperty (obj.__proto__, prop);/or recursive
  else return
    undefined;


Example: Finding the Say method for P objects

<script type= "Text/javascript" >
  /* Find the Prop attribute of the Obj object */
   function GetProperty (obj, prop) {
    if ( Obj.hasownproperty (prop)) return
      Obj[prop];
    else if (obj.__proto__!== null) return
      GetProperty (obj.__proto__, prop);/or recursive
    else return
      undefined;
  the var person = function () {};//defines the person class
  Person.prototype.Say = function () {
    alert ("Person Say");
  }
  Person.prototype.Salary = 50000;
  var programmer = function () {};//defines programmer class
  //programmer.prototype = new Person ()//Let the programmer class inherit from the class, writing a
  Programmer.prototype = person.prototype;//Let the programmer class inherit from the human class, writing two
  Programmer.prototype.WriteCode = function () {
    Alert ("Programmer writes Code");
  Programmer.prototype.Salary = +;
  var p = new programmer ();
  var sayfn = GetProperty (P, "Say");//Find the Say method of the P object
  sayfn.call (p);//Call Say method found
</script>

The results of the operation under Firefox:

In fact, prototype is only an illusion, he is in the realization of the prototype chain has only played an auxiliary role, in other words, he is only in New times have a certain value, and the essence of the prototype chain, in fact, is __proto__.

I hope this article will help you with JavaScript programming.

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.