Inheritance and prototype in JavaScript

Source: Internet
Author: User

Before learning JS is just w3school on the basic grammar to see once, and then when the fine reading, the book will appear many many not heard of the grammar, one of which is JS inheritance and always see the prototype. I mainly look at the two JS book is the "JavaScript authoritative guide", that is the Rhino book, there is a crazy xx series of "Mad Html5/css3/javascript handout." The former is very suitable for the use of the JS details, if you need to learn some JS internal mechanisms and related content, the big bite up or very taste. The latter is a quick textbook that gives you a very comfortable way to open a concept that is not obscure and easy to understand. If you have not learned anything after reading W3school, you should try to read the book, this is the tip I just started learning tips.

First talk about inheritance, in JS is actually no concept of inheritance. But you should all know that in object-oriented programming, there is a display of inheritance between classes, a class can be shown to specify which class to inherit from, and then the inherited subclass will have the properties and methods of the parent class. JS does not have this concept, but it is a similar inherited method to extend the original class. This is done by using the prototype property of the class to dynamically add properties and methods to the class, which is similar to inheritance, but it can only be called "pseudo-inheritance" because the essence of this inheritance is to modify the original class rather than to produce a subclass.

We first say without inheriting, JS through what method to add properties and methods for the object.

First, when a program assigns a value to an object that does not exist, it can be thought of as adding a property to the object.

"Code 01"

                              var obj = {};                              Obj.name = "Jeremy";                              Obj.info = function () {                                  Console.log ("This is a method");                              

Inserting here illustrates the conceptual understanding of functions, methods, objects, and classes.

function, in JavaScript there is a "class citizen" said, when the definition of a function in JS, is actually generated the following:

1) Function: Java-like method, it can be called;

2) object: When a function is defined, the system creates an object, which is an instance of function class;

3) Method: When a function is defined, the function is appended to an object as a method of an object:

"Code 02"

                              function Person (name,gender) {var val = "ValueName";//local variable this.name = Name;this.gender = gender;//defines an anonymous function. The equivalent of the info method specified for the person object this.info = function () {Console.log ("name:" +this.name); Console.log ("Gender:" +this.gender); Console.log ("val:" +val);}} var p1 = new Person (' Jeremy ', ' Male ');//instance P1 to call method info () var v = p1.info (); Console.log ("can access to local variable val:" +v);
4) Class: When defining a function, you get a class with the same name as the function, and this function is the constructor of the class , so when you define a function, the actual

is to define a constructor .

Let's take a look at the code 02 above.

The program defines a function person, which also defines the person class, the constructor of the class, which provides the info method for the person instance P1.

Although we have also completed the method of increasing the number of person, there are some problems in doing so. For example, performance will be low, each time you create a person object, there will be a lot of info functions, which will cause system memory leaks (actually what I did not explore), causing performance degradation. There is also a very obvious problem, know that the JS closure of friends should be found, in the info () function to access the local variable val, formed a closure (here is not the closure of the expansion said). This, however, causes the scope of the Val variable to widen, and at the end of the code, the program can still access the local variable value.

So! In order to avoid the occurrence of these bad things! We recommend that you use the prototype property.

First in JavaScript, each JavaScript object (except NULL) is associated with another object, which is a prototype, and each object in JS inherits properties from the prototype. Within the 3 methods of creating objects, objects created by the object's direct volume have the same object prototype, and a reference to the object's prototype can be obtained through object.prototype. The prototype of the object created by the keyword new and the constructor is even the value of the prototype of the constructor. As a result, objects created from new object () are also inherited from Object.prototype, as is the case with Var empty={};

The object direct volume creation object is a mapping table that consists of several name/value pairs. Just like this:

Var empty={};//property is an empty object var person={name: "Gua", Age: "18"};//with the value of the name and age property
The New keyword Creation object creates and initializes an object with the newly keyword. The form is new followed by a function call, where the function is called the constructor (constructor), which
The constructor is used to initialize a newly created object. Just like this:
var obj = new Object (), var arr = new Array ();
In other words, the JS object is an instance of the same base class (object).
Well, I also think this paragraph is more obscure.
Well, let's see how the code is implemented.
function Person (name,gender) {this.name = Name;this.gender = gender;//defines an anonymous function. The equivalent of the info method specified for the person object this.info = function () {Console.log ("name:" +this.name), Console.log ("Gender:" +this.gender);}} var p1 = new Person (' Jeremy ', ' Male ');p 1.info ();//adds walk function for the prototype attribute of the person class. That is, you can think of dynamically increasing the walk instance method for the person class Person.prototype.walk = function () {Console.log (this.name + "walking ...). Step-by-step ... "); var p2 = new Person (' Guagua ', ' female ');p 2.info ();//Walk method to perform P2 p2.walk ();        JS has increased the method walk for the class person dynamic, so P1 also has the walk method. P1.walk ();
                

Operation Result:

This procedure uses prototype to add a walk method to the person class, which allows all the person instances to share a walk method, and the walk method is not within the person function, so no closures are generated.

So we should avoid using inline functions to define methods for classes, and add methods by adding prototype properties.

The above is my recent reading to learn some of the content, there is no place to hope that you correct.

Inheritance and prototype in JavaScript

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.