Small Example of js simulation class inheritance

Source: Internet
Author: User

Copy codeThe Code is as follows:
// Use prototype inheritance, and use a temporary object as the Child prototype property in the middle. The prototype property of the temporary object then points to the prototype of the parent class,
// Prevent all subclass and parent class prototype attributes from pointing to an object.
// When the prototype attribute of the subclass is modified, other subclasses and parent classes will not be affected.
Function extend (Child, Parent ){
Var F = function (){};
F. prototype = Parent. prototype;
Child. prototype = new F ();
Child. prototype. constructor = Child;
Child. base = Parent. prototype;
}

Function Parent (name)
{
This. aa = 123;
This. getName = function () {return name;}; // use a closure to simulate a private member
This. setName = function (value) {name = value ;};
}
Parent. prototype. print = function () {alert ("print! ");};
Parent. prototype. hello = function ()
{
Alert (this. getName () + "Parent ")
};

Function Child (name, age)
{
Parent. apply (this, arguments); // call the Parent class constructor to inherit the attributes defined by the Parent class
This. age = age;
}
Extend (Child, Parent); // inherits Parent

Child. prototype. hello = function () // rewrite the hello method of the parent class
{
Alert (this. getName () + "Child ");

Parent. prototype. hello. apply (this, arguments); // call the method with the same name as the Parent class
};
// Subclass Method
Child. prototype. doSomething = function () {alert (this. age + "Child doSomething ");};

Var p1 = new Child ("xhan", 22 );

Var p2 = new Child ("xxx", 33 );

P1.hello ();
P2.hello ();

P1.doSomething (); // subclass Method
P1.print (); // parent class Method

Alert (p1 instanceof Child); // true
Alert (p1 instanceof Parent); // true

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.