It is helpful for beginners to learn about JavaScript object-oriented and inheritance.

Source: Internet
Author: User

This is an article about object-oriented and Inheritance of JavaScript. It was written one year ago. The author has made a step-by-step process. It is very helpful for those who want to learn object-oriented in JavaScript. Therefore, I try to translate it, correct the error. Objects and Inheritance in Javascript

Although some Javascript users may never need to know the nature of the prototype or object-oriented language, however, developers from traditional object-oriented languages may find the inheritance model of JavaScript very strange. Different JS frameworks provide their own methods to compile class-like code, which makes JavaScript object-oriented more difficult to understand. The result is:
1. There is no standard method to implement object-oriented.
2. The underlying concepts of JS object-oriented are not well known.

Prototype inheritance
Prototype inheritance is a very simple concept. Its essence is:
1. If object a inherits from object B, B is the prototype of object ).
2. a inherits all the attributes of B. That is, if the value of B. x is 1, the value of a. x is 1.
3. attributes of a rewrite attributes with the same name in B.

Let's look at the effect in the specific code. Suppose there is a John Smith and a Jane inherited from him.

Copy codeThe Code is as follows: var john = {firstName: 'john', lastName: 'Smith '};
Var jane = {firstName: 'jar '};
Jane. _ proto _ = john;

Now john is the prototype of jane. jane inherits all the attributes of john.Copy codeThe Code is as follows: jane. lastName
"Smith" // This property is inherited from john

The attributes of jane have a higher priority, as shown below:Copy codeThe Code is as follows: jane. firstName; // This attribute overwrites the firstName attribute in john.
"Jane"

If john adds an attribute after this, jane dynamically inherits this attribute, as shown below:Copy codeThe Code is as follows: john. hair = 'brown '; // Add a new attribute to john.
Jane. hair;
"Brown" // The result indicates that jane inherits the newly added attribute.

Now let's assume that jane is married, so she has a new surname (last name)Copy codeThe Code is as follows: jane. lastName = 'doe'

This attribute overwrites the attribute (lastName) of the same name in john)Copy codeThe Code is as follows: jane. lastName
"Doe"

However, if we delete jane's lastNameCopy codeThe Code is as follows: delete jane. lastName
The value of this attribute is restored to the value of john.
[Code]
Jane. lastName
"Smith"

Now, jane can inherit from other objects. There can be any number of inheritance in this chain. We call it prototype chain. In fact, john also has a prototype attribute.Copy codeThe Code is as follows: john. _ proto __;
Object {}

In the Firebug console, the value of john. _ proto _ is set to Object {}, but Object {} represents the Object. prototype-the parent class of all objects.

This is a brief description of prototype inheritance. It looks good, right?
However, in fact, we cannot use _ proto...

Tell everyone a bad message ......
IE does not support the _ proto _ attribute. In fact, __proto _ is not an attribute in the ECMAScript specification. Mozilla also intends to remove this attribute in Versions later than Firefox.

However, this does not mean that the _ proto _ attribute does not exist. Although the _ proto _ attribute cannot be directly accessed in Some browsers, it still exists in some form and we have to deal with it, but it is not so direct.

Class and inheritance
Therefore, we can say that JavaScript has no class
Remember: no class in JavaScript
In this case, how can methods and inheritance be implemented?
Prototype ). In traditional object-oriented languages, methods depend on classes, while in JavaScript, methods depend on the prototype of objects, the prototype is bound with the constructor of the object.

In JavaScript, functions act as constructor. By using the new operator, you can use a function as a constructor. The following code creates a Cat function:Copy codeCode: function Cat (name) {// <-this is a common function.
This. name = name // this indicates the new object.
}

The above code will automatically create a Cat. prototype objectCopy codeThe Code is as follows: Cat. prototype
Cat {}

We can use the new operator to create an instance of Cat.Copy codeCode: var garfield = new Cat ('garfield ') // create an instance. The Cat function acts as the constructor.

Now, the Cat. prototype object becomes the prototype of all the objects created through new Cat (), for example:Copy codeThe Code is as follows: garfield. _ proto _ = Cat. prototype
True // do you see it? 'Cat. prototype' is the prototype of the garfield object.

Now, we add a method for Cat. prototype. After the method is added, the method can be accessed by garfieldCopy codeThe Code is as follows: Cat. prototype. greet = function (){
Console. log ('meow, I am '+ this. name)
}
Garfield. greet ()
"Meow, I am Garfield"

Other Cat instances can also accessCopy codeCode: var felix = new Cat ('Felix ')
Felix. greet ()
"Meow, I am Felix"

Therefore, in JavaScript, a method is dependent on the prototype of an object.

In fact, we can also add a method for garfield, which overwrites the Same Name method in Cat. prototype, as shown below:Copy codeThe Code is as follows: garfield. greet = function (){
Console. log ("What's new? ");
};
Garfield. greet ();
"What's new? "

However, this does not affect other objects.Copy codeThe Code is as follows: felix. greet ();
"Meow, I am Felix"

Therefore, in JavaScript, a method can be directly associated with an object, can be associated with the object prototype, or can be associated with any parent object of the object, that is, it can be associated with any link of the prototype chain. Inheritance is implemented in this way.

To create a prototype chain, first create another constructor called Animal?Copy codeThe Code is as follows: function Animal (){
}

Next, we need to point the prototype of Cat. prototype to an Animal object, so that the Cat instance will inherit all the Animal methods. Therefore, we set the Cat. prototype value to the Animal instance, as shown below:Copy codeThe Code is as follows: Cat. prototype = new Animal ();

In addition, we also need to tell the new Cat. prototype, which is actually an instance of Cat:Copy codeThe Code is as follows: Cat. prototype. constructor = Cat // Let 'cat. prototype' know that it is an instance of Cat.

Although this is mainly for the hierarchical relationship between classes, it is usually necessary to do so.

Now, since the objects inherited from Animal. prototype and Cat. prototype belong to Animal classes, all Cat instances indirectly inherit from Animal. prototype. If we add a new method to Animal. prototype, all Cat instances can also access this method.Copy codeThe Code is as follows: Animal. prototype. breed = function (){
Console. log ('making a new animal! ');
Return new this. constructor ();
};
Var kitty = garfield. breed ();
Making a new animal!

With the above Code, we have implemented inheritance, which is simple.

Conclusion
Although prototype-based inheritance in JavaScript is strange and takes some time to get used to it, his core idea is very simple. As long as you really understand these essential concepts, you will have the confidence to control JavaScript OO in these mixed codes. (End) ^_^

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.