Prototype and inheritance in JavaScript-

Source: Internet
Author: User
All objects in JavaScript are objects. This refers to objects in the traditional sense, that is, "a single entity that contains state and behavior ". For example, an array in JavaScript contains several values and contains objects of the push, reverse, and pop methods ....,. Please forget all the object-oriented knowledge you have learned before. Here you only need to consider the situation of racing cars. Yes, it's a racing car.


Recently, I was watching 24 Hours of Le Mans, a popular competition in France. The fastest car is called the Le Mans prototype car. Although these cars are made by Audi or Peugeot, they are not what you see on the street or on highways **. They are designed to participate in high-speed endurance events.


Manufacturers have invested a huge amount of money to develop, design, and manufacture prototype vehicles, and engineers are always trying to make this project the best. They have carried out various experiments on the compound composition and safety characteristics of alloy, bio-fuel, braking technology, and tires. Over time, some of the technologies in these experiments have been repeatedly improved, and they have entered the mainstream product line of vehicles. Some of the techniques you drive may have made your first appearance on a car prototype.


You can also say that these mainstream vehicles inherit the technical prototype from the racing car.


Now, we have discussed the basis of prototype and inheritance in JavaScript. Although it is not like the classic inheritance mode you know in C ++, Java or C #, it is equally powerful and may be more flexible.


Objects and Classes


All objects in JavaScript are objects. This refers to objects in the traditional sense, that is, "a single entity that contains state and behavior ". For example, an array in JavaScript contains several values and contains objects of the push, reverse, and pop methods.

var myArray = [1, 2];myArray.push(3);myArray.reverse();myArray.pop();var length = myArray.length;



Now the question is, where does push come from? The static languages we mentioned earlier use "Class syntax" to define the object structure, but JavaScript is a language without "Class syntax, you cannot use the Array "class" syntax to define each Array object. Because JavaScript is a dynamic language, we can place Methods on objects as needed. For example, the following code defines the vertex object used to represent a vertex in a two-dimensional space, and defines an add method.



var point = {    x : 10,    y : 5,    add: function(otherPoint) {        this.x += otherPoint.x;        this.y += otherPoint.y;    }};




However, the above practice is not scalable. We need to ensure that each vertex object contains an add method, and we also want all vertex objects to share the implementation of the same add method, rather than manually adding each vertex object to this method. This is where the prototype plays its role.


Prototype


In JavaScript, each object remains in a hidden state-a reference to another object, also known as a prototype. The array we created previously references a prototype object, as is the point object we created ourselves. As mentioned above, prototype references are hidden, but ECMAScript (the official JavaScript name) can be implemented through the _ proto _ attribute of an object (such as Google Chrome) access this prototype reference. In terms of concept, we can regard an object as a prototype relationship similar to the object it represents.



The magic of the original JavaScript model is how multiple objects maintain reference to the same prototype object. For example, if we create two Arrays:

var myArray = [1, 2];var yourArray = [4, 5, 6];


The two arrays will share the same prototype object, and the following code calculates the result as true:

Object.getPrototypeOf(myArray) === Object.getPrototypeOf(yourArray);

If we reference the push method on two array objects, JavaScript will look for the push method shared on the prototype.

// This will return true: typeof (Array) = "function" // The expression is also: Object. getPrototypeOf (Array) === Object. getPrototypeOf (function () {}) // The expression is also: Array. prototype! = Null


The first line in the Code proves that arrays in JavaScript are functions. Later we will see how to call the Array Function to create a new Array object. The next line of code proves that the Array object uses the same prototype as any other function object, just as we can see that the Array objects share the same prototype. The last line of code indicates that the Array function has a prototype attribute, which points to a valid object. This prototype attribute is very important.

Every function object in JavaScript has the prototype attribute. Do not confuse the _ proto _ attribute of this prototype attribute. They have different purposes and do not point to the same object.

// Returns trueObject. getPrototypeOf (Array )! = Array. prototype

Array. _ proto _ provides an Array prototype-use it as the object inherited by the Array Function.


Array. protoype provides prototype objects of all arrays. That is to say, it provides a prototype object for an array object like myArray, and also contains methods that all arrays will inherit. We can write some code to prove this fact.


// TrueArray. prototype = Object. getPrototypeOf (myArray) // It is also trueArray. prototype = Object. getPrototypeOf (yourArray );


We can also use this new knowledge before re-painting.

Create a new empty object

Var o ={}; // inherits from the same prototype, an array object o. _ proto _ = Array. prototype; // now we can call any method of the array... o. push (3 );


Although this code is interesting and can work, the problem is that not every JavaScript Environment supports writable _ proto _ object attributes. Fortunately, JavaScript does have a built-in standard mechanism for object creation. You only need an operator to create a new object, and set the _ proto _ reference of the new object-that is, the "new" operator.

var o = new Array();o.push(3);


The new operator in JavaScript has three basic tasks. First, it creates a new empty object. Next, it sets the _ proto _ attribute of the new object to match the prototype attribute of the called function. Finally, the operator calls the function and transmits the new object as a "this" reference. If you want to expand the last two lines of code, it will become the following:


var o = {};o.__proto__ = Array.prototype;Array.call(o);o.push(3);


The call method of the function allows you to specify the object referenced by "this" in the function when calling the function. Of course, the author of the function needs to implement such a function in this case. Once the author creates such a function, it can be called a constructor.


Constructor


Constructor is the same as a common function, but has the following two special properties.


Usually the first letter of the constructor is capitalized (making it easier to recognize the constructor ).

Constructors are usually combined with the new operator to construct new objects.

Array is an example of a constructor. The Array function must be used with the new operator, and the first letter of the Array is uppercase. JavaScript includes Array as a built-in function, and anyone can write their own constructor. In fact, we can compile the constructor for the vertex object created earlier.


var Point = function (x, y) {    this.x = x;    this.y = y;    this.add = function (otherPoint) {        this.x += otherPoint.x;        this.y += otherPoint.y;    }}var p1 = new Point(3, 4);var p2 = new Point(8, 6);p1.add(p2);



In the above Code, we use the new operator and the Point function to construct a vertex object. This object has the x and y attributes and an add method. You can figure 6 the final result.

The problem is that each vertex object still has a separate add method. Using the prototype and inherited knowledge we learned, we prefer to transfer the add method of the vertex object from each vertex instance to Point. prototype. To inherit the add method, we need to modify the Point. prototype object.

var Point = function (x, y) {    this.x = x;    this.y = y;}Point.prototype.add = function (otherPoint) {    this.x += otherPoint.x;    this.y += otherPoint.y;}var p1 = new Point(3, 4);var p2 = new Point(8, 6);p1.add(p2);


Success! We just completed the inheritance mode of the original type in JavaScript!

The above is the prototype and inherited content in JavaScript. For more information, see the PHP Chinese website (www.php1.cn )!

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.