Introduction of JavaScript prototypes in plain language

Source: Internet
Author: User

prototypes (prototype) are basic concepts that every JavaScript developer must understand, and the goal of this article is to explain JavaScript prototypes in a popular and detailed manner. If you do not understand the JavaScript prototype after reading this post, please write your question in the comments below and I will answer all the questions myself.

To understand the prototypes in JavaScript, you have to understand JavaScript objects. If you are not familiar with the object, you need to read my article JavaScript Objects in Detail (translation: detailed JavaScript object). And you know that the attribute is the variable defined in the function.

There are two concepts in JavaScript that are associated with one another:

1. First, each JavaScript function has a prototype attribute, and you attach properties and methods to the stereotype attribute when you need to implement the inheritance. Note that this stereotype property is not enumerable: it is not available in the for/in loop. But Firefox and most versions of Safari and Chrome have a __proto__ "pseudo" attribute (a choice) that allows you to access the properties of the object's prototype. You may never have used this _proto__ pseudo attribute, but you need to know it exists and it is an easy way to access the prototype properties of an object in some browsers.

Object prototypes are primarily used for inheritance: You add methods and properties to the object's prototype properties so that the prototypes and attributes exist in the instance of the function.

The following is a simple example of using primitive attribute inheritance (more on inheritance later):

function Printstuff (mydocuments) {    this.documents = mydocuments;} We add the method print () for Printstuff's prototype property, so that other instances (objects) can inherit this method PrintStuff.prototype.print = function () {    Console.log ( this.documents);} Create a new object with the constructor Printstuff () so that the new object inherits the properties and methods of Printstuff. var newObj = new Printstuff ("I am a new Object and I can print."); /newobj inherits all the properties and methods of the function Printstuff, including the method print. Now newobj can call print directly, even though we have never defined method print () for it. Newobj.print (); I am a new Object and I can print.

2. The second concept of JavaScript prototypes is the prototype feature. To think of the archetypal characteristics as a property of the object, which indicates the "parent" of the object. In short: the archetypal nature of an object can be seen as the "parent" of the object-the place where the object obtains its attributes. Object properties are often referred to as prototype objects, and it is created automatically when you create an object. The explanation for this is that each object inherits properties from one of the other objects, and here "some other object" is the prototype attribute or "parent" of the object. (You can think of archetypal traits as a blood relationship or a parent). In the code of the example above, the prototype of newobj is Printstuff.prototype.

Note: All objects have attributes, just as object properties have their own attributes. Object attributes are prototypes, classes, and extended attributes. These are the archetypal features we'll discuss in the second example.

It is also important to note that the pseudo attribute __proto__ contains the prototype object of an object (the parent object that inherits methods and properties from the object).

Important//constructors///Before we continue reading, let's examine the constructors briefly. The constructor is a function that initializes the new object and invokes the constructor with the new keyword. For example: function account () {}//This is the use of the constructor account to create an object Useraccountvar UserAccount = new account (); Also, all objects that inherit from another object inherit the constructor properties of that object. This constructor property is a property (as with any variable) that holds or points to the object's constructor. The constructor for this example is Object () var myObj = new Object ();//And if you later want to know the constructor of MYOBJ: Console.log (Myobj.constructor); Object ()//Another example: Account () is a constructor var useraccount = new account (); View the Object UserAccount constructor Console.log (useraccount.constructor); Account ()

Prototype properties of objects created with the new object () or object type

All objects created by object or constructor object inherit from Object.prototype. So Object.prototype is the prototype attribute (or prototype object) of all objects created with object () or {}. Object.prototype itself does not inherit any of the methods or properties from any other object.

The object useraccount inherits from object and therefore its archetypal nature is Object.prototype.var UserAccount = new Object ();//This declaration uses object-style to create objects UserAccount The object useraccount inherits from object, so, just like the above object UserAccount, its archetypal nature is object.prototype. var useraccount = {name: "Mike"}

prototype properties of objects created with constructors

Derive their constructors from the new keyword and any object created from the constructor of any non-object ().

For example:

function account () {}var useraccount = new Account ()//initializes the UserAccount with the constructor account () and therefore its prototype feature (prototype object) is Account.prototyp E.

Similarly, any array, such as var myArray = new Array (), obtains the prototype from Array.prototype and inherits the properties of Array.prototype.

Therefore, when an object is created there are two common ways to build the object's prototype properties:

1. If the object was created using the object formula (var newObj = {}), it inherits the property from Object.prototype, and we say that its prototype object (or prototype attribute) is Object.prototype.

2. If the object is created using a constructor, such as new object () or new Fruit () or new Array () or new anything (), then it inherits from the constructor (object (), Fruit (), Array (), or anything ()). For example, with a function such as Fruit (), each time we create an instance of a new fruit (var afruit = new Fruit ()), then the prototype of the new instance comes from the constructor Fruit, which is fruit.prototype. Any object created with the new Array () will use Array.prototype as its prototype. Any object created with the constructor object (OBJ (), such as var anobj = new Object (), inherits from Object.prototype.

One more thing you need to know, in ECMAScript 5, you can create objects with a method object.create () that allows you to specify a prototype of the new object. We will learn ECMAScript 5 in a follow-up article.

Why is prototyping important and when to use prototypes?

There are two important uses for JavaScript, as mentioned in the previous article:

1. Prototype properties: Prototype-based inheritance

The reason why JavaScript is important is that JavaScript does not have the classic class-based inheritance (in most object-oriented languages), so all JavaScript inheritance is done through the prototype properties. JavaScript has a mechanism based on prototype inheritance. Inheritance is a programming specification that enables objects (or classes in other languages) to inherit properties and methods from other objects (or classes). In JavaScript, inheritance is implemented through prototypes. For example, you can create a fruit function (that is, an object, because all JavaScript functions are objects) and add properties and methods to this fruit's prototype property, then all instances of the fruit function inherit fruit all properties and methods.

Examples of inheritance in javascript:

function Plant () {this.country = "Mexico"; This.isorganic = true;} Add method Shownameandcolor to plant prototype property Plant.prototype.showNameAndColor =function () {console.log ("I am a" + THIS.name + " And my color is "+ This.color);} Add method Amiorganic to plant prototype Property Plant.prototype.amIOrganic = function () {if (this.isorganic) console.log ("I am org Anic, baby! ");}    function Fruit (fruitname, fruitcolor) {this.name = Fruitname; This.color = Fruitcolor;} The fruit prototype is set to the Plant constructor, thus inheriting all plant.prototype methods and properties Fruit.prototype = new Plant ();//Creating a new fruit with the constructor Abananavar Abanana = new Fruit ("Banana", "Yellow");//Here Abanana uses the name attribute from Abanana object prototype Fruit.prototype: Console.log (Abanana.name) ; banana//is Shownameandcolor with the method from the Fruit object prototype Plant.prototype. The Abanana object inherits all the properties and methods from the functions plant and Fruit console.log (Abanana.shownameandcolor ()); I am a Banana and my color is yellow. 

Note that although the method Shownameandcolor is defined on the prototype chain of the object Plant.prototype, this method is inherited by the object Abanana.

In fact, any object that uses the constructor fruit () inherits all of the properties and methods of Fruit.prototype and all of the attributes and methods from the fruit prototype Plant.prototype. This is the main way to implement inheritance in JavaScript and the integration role that the prototype chain plays in this process.

2. Prototype feature: Get the properties of an object

Prototypes are also important for getting the methods and properties of an object. Archetypal attributes (or prototype objects) are "parent" objects of inheritable properties that are originally defined for these "parent" objects. It's a bit like you can get from your father-he's your "prototype parent", where you inherit your last name. If we want to know where your last name comes from, we will first see if you have given yourself this surname, and if not, we will continue to see if you inherited the surname from your father. If this surname is not your father's, then we will continue to look at your father's father's surname (your father's father's archetype).

Similarly, if you want to get a prototype of an object, you'll start looking directly at the object's properties. If the JS runtime is no longer able to find the property, it will go to the object's prototype-where the object gets its properties, to see the property.

If the attribute is not found in the object's prototype, the search for that property is transferred to the prototype of the object (the father of the object, Grandpa). So it lasted until there was no prototype (no more great-grandfather; no more hereditary kinship). This is actually the prototype chain: a continuous upward chain from the prototype of the object to the prototype of the object. And JavaScript uses this prototype chain to search for properties and methods of objects.

If a property does not exist in the prototype of any of the objects on its entire prototype chain, then this property does not exist and returns undefined.

This prototype chain mechanism is essentially the same concept as the prototype-based inheritance we discussed above, but here we focus more on how JavaScript obtains properties and methods of objects through object prototypes.

This example demonstrates the prototype chain of an object's prototype object:

var myfriends = {name: "Pete"};//in order to find the following attribute name, the search starts directly from the object Myfriends, and the property name is found immediately, because we have defined the property name for the object myfriends. This can be imagined as having a link to the prototype chain. Console.log (myfriends.name);//In this example, the Search method ToString () is started from the object myfriends, but because we have never created a method tostring for the object myfriends, The compiler will then go to Myfriends's prototype (the object that is Myfriends inherited property). And since all objects created with object style inherit from Object.prototype, the method ToString will be Found in Object.prototype--about all attributes inherited from Object.prototype, see important tips below myfriends.tostring ();

Important Notes

The properties of the Object.prototype that all objects will inherit

The properties and methods of all objects in JavaScript inherit from Object.prototype. These inherited attributes and methods have constructors, hasOwnProperty (), isprototypeof (), propertyisenumerable (), tolocalestring (), toString (), and Valueo F (). There are four new ways to access Object.prototype in ECMAScript 5.

Here is an example of another prototype chain:

function people () {    This.superstar = "Michael Jackson";} Define the attribute "athlete" for the People prototype so that "athlete" can be accessed by all objects that use the constructor people (). People.prototype.athlete = "Tiger Woods"; var Famousperson = new People (); Famousperson.superstar = "Steve Jobs";//For Super Star's search will first see if the object Famousperson has attribute superstar, and because that is the attribute that is defined there, this is the property that needs to be used. Because we have repeatedly defined the property superstar of the chain Famousperson for the object Famousperson, the search for superstar will not continue to rise on the prototype chain. Console.log (Famousperson.superstar); Steve jobs//Note that in ECMAScript 5 you can set the property to read-only so that you can't repeat the attribute as we just did. This shows the properties from the Famousperson prototype (People.prototype), because the property athlete is not defined for the object Famousperson itself. Console.log (Famousperson.athlete); Tiger woods//in this case, Search up on the prototype chain and find the method tostring in Object.prototype, this method comes from the inheritance of object fruit--as we mentioned earlier, all objects eventually inherit from Object.prototypeconsole.log ( Famousperson.tostring ()); [Object Object]

All established constructors (Array (), number (), String (), etc.) Are created by the constructor object, so their prototypes are object.prototype.

Introducing JavaScript prototypes in plain language

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.