JS Simulation class Inheritance Small example _javascript skill

Source: Internet
Author: User
Copy Code code as follows:

Using prototype inheritance, a temporary object is used as the prototype property of the child, and the prototype property of the temporary object points to the prototype of the parent class.
Prevents all subclass and parent-class stereotype properties from pointing to a pass object.
This will not affect other subclasses and parent classes when you modify the stereotype properties of subclasses
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;}; Using closures to simulate private members
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 properties defined by the parent class
This.age = age;
}
Extend (child,parent); Inherit parent

Child.prototype.hello = function ()//rewrite the parent Hello method
{
Alert (This.getname () + "Child");

Parent.prototype.hello.apply (this,arguments); Calling the parent class with the same name method
};
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.