"JavaScript" JS implements the most common method of inheriting __java

Source: Internet
Author: User

Since JavaScript is OOP programming, there must be a concept of inheritance. Internet search a bit, more chaotic, here I do a summary.

There are roughly three ways:

1, Apply/call, can not inherit the prototype;

2, prototype, the parent constructor has parameters when it loses the meaning of inheritance, it becomes a new object;

3, Apply/call and prototype mixed use.

Among them, the most common is the third, the code is as follows:

function A () {
    A.prototype.name= "Jack";
    function B () {
        a.apply (this);//Inherit A's own property
        this.sex= "Remale";
    B.prototype = Object.create (A.prototype);//very critical, create an empty object to inherit the prototype of the parent class to ensure that the parent class is not modified
    //b.prototype = a.prototype;//must not write this, Writing this will change the value of the attribute on the parent prototype.
    B.prototype.constructor = b;//This sentence has no effect on the structure, just to inherit the consistency of the structure, otherwise the construtor points to a.
    var b = new B ();
    Alert ("An attribute on the archetype of a:" +b.name);
    Alert ("A's own property:" +b.age);
    Alert ("B's Own property:" +b.sex);
The previous two methods have problems, do not paste, attached link: http://blog.csdn.net/kkkkkxiaofei/article/details/46474069

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.