Js object-oriented --- inheritance

Source: Internet
Author: User

 

JavaScript has no integrated object, so we use the following three methods to simulate it:

 

 

1. js prototype implementation inheritance

Function Person (name, age ){

This. name = name;

This. age = age;

}

Person. prototype. sayHello = function (){

Document. write ("Use the prototype to get Name:" + this. name + "</br> ");

}

 

// Var per = new Person ("zhangping", "21 ");

// Per. sayHello ();

 

 

Function Student (){}

Student. prototype = new Person ("zhangping", "21 ");

Var stu = new Student ();

Student. prototype. gade = "3 ";

Student. prototype. intr = function (){

Document. write (this. gade );

}

Stu. sayHello ();

Stu. intr ();

*/

2. constructor implementation inheritance

/*

Function Parent (name ){

This. name = name;

This. sayParent = function (){

Document. write ("Parent:" + this. name );

}

}

Function Child (name, age ){

This. tempMethod = Parent;

This. tempMethod (name );

/* Www.2cto.com

This. age = age;

This. sayParent = function (){

Document. write ("Child:" + this. name + "age:" + this. age );

}

*/

/*

}

Var parent = new Parent ("zhangping ");

Parent. sayParent ();

Var child = new Child ("xiaoguanxianfei", "11 ");

Child. sayParent ();

*/

 

3. Use Call Applay to implement inheritance

 

Function Person (name, age, love ){

This. name = name;

This. age = age;

This. love = love;

This. say = function say (){

Document. write ("name:" + name );

}

}

Function student (name, age ){

Person. call (this, name, age );

}

Function teacher (name, love ){

Person. apply (this, [name, love]);

}

Var per = new Person ("zhangping", "21", "guanxianfei ");

Per. say ();

Var stu = new student ("guanxianfei", "22 ");

Stu. say ();

Var tea = new teacher ("xiaoguanxianfei", "22 ");

Tea. say ();

From guanxianfei

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.