Introduction to the JavaScript prototype chain

Source: Internet
Author: User

Javascript is a prototype-based programming language, which is very different from the class-based programming language, I will list the following important points:

  1. The function is a first class object, that is, the function has the same language status as the object.
  2. No class, only objects
  3. A function is also an object called a function object.
  4. Objects are passed by reference.

How can we implement inheritance in this prototype based programming language (a major basic element of OO)? This is also the origin of prototype.

See the following code snippet:

function foo(a, b, c){return a*b*c;}alert(foo.length);alert(typeof foo.constructor);alert(typeof foo.call);alert(typeof foo.apply);alert(typeof foo.prototype);  

After running the above Code in a browser, you will find that:

  1. Length: Number of function parameters
  2. Prototype: an object
  3. The other three are functions.

For any function declaration, it will have the five properties (methods or attributes) described above ).

The following describes prototype.

// Prototypefunction Person (name, gender) {this. name = name; this. gender = gender; this. whoAreYou = function () {// this is also called closure. Internal functions can access the variable var res = "I'm" + this. name + "and I'm a" + this. gender + ". "; return res ;};}// the object created by Person has the following attributes: Person. prototype. age = 24; Person. prototype. getAge = function () {return this. age ;}; flag = true; if (flag) {var fun = new Person ("Tower", "male"); alert (fun. name); alert (fun. gender); alert (fun. whoAreYou (); alert (fun. getAge ();} Person. prototype. salary = 10000; Person. prototype. getSalary = function () {return this. name + "can earn about" + this. salary + "RMB each month. ";}; // The following is the most amazing thing. We changed the Person prototype, this change is made after fun is created // and makes fun have the same attributes and Methods // inherited meaning that this if (flag) {alert (fun. getSalary (); alert (fun. constructor. prototype. age); // and this is equivalent to directly calling Person. prototype. agealert (Person. prototype. age );}

From the above example, we can find that we can dynamically add prototype methods or attributes, and the objects created by them will automatically inherit related methods and attributes.

In addition, each object has a constructor attribute, which is used to point to the function object for creating it. In the preceding example, fun. constructor points to Person.

Then a question arises naturally. What is the difference between the methods and attributes declared by function objects and the objects declared by prototype?

There are several differences:

  1. The declared methods and attributes are static. That is to say, after you declare them, you try to add new methods or modify existing methods without affecting the objects created by them, that is, the inheritance fails.
  2. Prototype can dynamically add new methods or modify existing methods, but dynamically once the parent function object declares the relevant prototype attribute, objects Created by the prototype automatically inherit the attributes of the prototype.

Continue with the above example:

Flag = true; // The method declared inside the function is static and cannot be passed by the Person. school = "ISCAS"; Person. whoAreYou = function () {return "zhutao" ;}; // The method for dynamically changing the declarative period does not affect the method of the object created by it, static if (flag) {alert (Person. school); alert (fun. school); // The output is "undefined" alert (Person. whoAreYou (); // output zhutaoalert (fun. whoAreYou (); // I'm Tower and I'm a male .} person. prototype. getSalary = function () {return "I can earn 1000000 USD" ;}; if (flag) {alert (fun. getSalary (); // it has inherited the change, that is, the so-called dynamic}

Since there are function objects and prototype attributes, how do I search for the corresponding attributes of the objects created by them?

Follow the steps and sequence below.

  1. First, search for the properties of the function object.
  2. If 1 is not found, the prototype attribute is searched. If 2 results are found, the prototype is directly executed. Otherwise, the prototype of the parent object is searched until it is found, or reach the end of prototype chain (the end will be the Object)

The above also answers the solution if the function object attributes are the same (with the same name) as the prototype attributes, the function object takes precedence.

Let's look at an example of multiple prototype chains:

// Example of multiple prototype chains function Employee (name) {this. name = ""; this. dept = "general"; this. gender = "unknown";} function WorkerBee () {this. projects = []; this. hasCar = false;} WorkerBee. prototype = new Employee; // The first level of prototype chain function Engineer () {this. dept = "engineer"; // overwrites "parent object" this. language = "javascript";} Engineer. prototype = new WorkerBee; // Level 2 prototype chain var jay = new Engineer ("Jay"); if (flag) {alert (jay. dept); // engineer, which finds its own alert (jay. hasCar); // false, the attribute alert (jay. gender); // unknown, which is the property of the previous layer}

The object relationships in the preceding example are as follows:

The prototype of javascript adds great flexibility to the language itself. However, compared with class-based programming, the entire thinking logic is still quite different. Therefore, we need to think more and learn more.

Javascript, however, is a functional language in the form of C language, which naturally requires more consideration.

Window. onload = function () {/* each object instance has a prototype property member that points to its instanceof object (temporarily referred to as the parent object) we call this layer-by-layer relationship to the parent prototype [prototype chian] prototype also has a parent prototype, because it is often an object instance, unless we artificially change it in JavaScript, "Everything is an object, and the function is the first type. "Both Function and Object are Function instances. The parent prototype of the Function points to the prototype of the Function. the prototype parent prototype is the Object prototype. The parent prototype of the Object also points to the Function prototype, Object. prototype is the top layer of all parent prototypes in the spiderMonkey engine. The parent prototype can be accessed through _ proto _. When you read the prototype, you can read several articles repeatedly to deepen your understanding, especially prototype, parent prototype, and prototype chain. * prototype refers to the parent prototype * _ proto _ accessing the prototype * instanceof parent class */Function of the prototype chain. prototype. hi = function () {alert ('Hi function');} Object. prototype. hi = function () {alert ('Hi object');} var a = function () {this.txt = 'A' ;};. prototype = {say: function () {alert ('A') ;}}; alert (a instanceof Function); // a is a Function instance; alert (. _ proto _ = Function. prototype); // The parent prototype of a points to the Function prototype; //. _ proto _ parent prototype Function // Function. prototype parent prototype Function alert (Function instanceof Object); // Function is an Object instance; alert (Function. _ proto _ = Function. prototype); // The parent prototype of the Function points to the prototype of the Function; alert (Function. prototype. _ proto _ = Object. prototype); // The parent prototype of the Function prototype directs to the Object prototype alert (Object. _ proto _ = Function. prototype); // The parent prototype of the Object pointing to the Function prototype; alert (Object. prototype. _ proto _); // the prototype of the Object is the top of all parent prototypes. It no longer has the parent prototype, so the result is null; alert (. prototype instanceof Object); // a prototype is also an Object alert (. prototype. _ proto _ = Object. prototype); // The parent prototype of a's prototype directs to the Object's 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.