How to Use prototype in JavaScript to implement inheritance

Source: Internet
Author: User
Prototype JavascriptWhat is prototype in? Kingsoft is just getting to know the prototype.

In msdn, prototype is interpreted as a reference to the object type prototype.

This passage is a very TMD abstraction, so confusing.

I saw it later.JavascriptAfter an authoritative guide, I probably understood the truth.

In the book, all objects have a prototype, which references the object. Although the prototype object is empty during initialization, any attributes you define in the prototype object will be inherited by all objects created by the constructor.

JS inheritance and classes have always been a strange thing. Here is an example to illustrate.

Rabbits are inherited from rodents. Other languages only need to inherit directly, but JS is different. js must declare an instance of a rodent before inheriting the rabbit class.

For example:
<SCRIPT>
Function cls1 ()
{
This. A = '000000 ';
}
Function cls2 (){}
Cls2.prototype = new cls1 ();
VaR o = new cls2 ();
Alert (O. );
</SCRIPT>

Of course, you may see this type of code in some advanced code.
<SCRIPT>
VaR o = {A: 123}
Function cls2 (){}
Cls2.prototype = O;
VaR x = new cls2 ();
Alert (X. );
</SCRIPT>
In fact, the same is true. O is a new object (); this method is simplified.

Provide additional information based on feedback.

However, any attribute you define in it will be inherited by all objects created by the constructor.

Understanding of this sentence
<SCRIPT>
Function cls1 (){}
Cls1.prototype. fun1 = function () {alert (123 );}
VaR o = new cls1 ();
O. fun1 ();
</SCRIPT>
In fact, there is no real prototype of cls1, but a fun1 attribute is added to the prototype of cls1.JavascriptRecorded
 

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.