Javascrip small examples of Inheritance

Source: Internet
Author: User

Copy codeThe Code is as follows:
// Inherit
Function Person (name, sex)
{
This. name = name;
This. sex = sex;
}
Person. prototype. sayName = function ()
{
Alert (this. name );
}
Person. prototype. saySex = function ()
{
Alert (this. sex );
}
Function Worker (name, sex, job)
{
// Inherit the person class
Person. call (this, name, sex) // here this refers to the instance of the Worker class, 'w' below, pass w to the Person constructor, in this case, W is disguised as this in the Person constructor.
This. job = job;
}

// Worker. prototype = Person. prototype; // if such a negative value is prototype, the sayJob method of the subclass, the Person parent class, also has the sayJob method, because it is a reference Transfer

// If it is changed to the following method, the Child class will not affect the parent class:
For (var I in Person. prototype)
{
Worker. prototype [I] = Person. prototype [I];
}

Worker. prototype. sayJob = function ()
{
Alert (this. job );
}

Var p = new Person ('lisi', 'male ');
// Alert (p. sayJob );

Var w = new Worker ('hangsan', 'male', 'soy sauce ');
W. sayName ();
W. saySex ();
W. sayJob ();
 

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.