Implementation of object inheritance in javascript: A small example _javascript skills

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

<! DOCTYPE html>
<meta charset= "UTF-8" >
<title>insert title here</title>
<script type= "Text/javascript" >
/**
* Format of JSON objects
{Key:value,key:value,key:value.}
*/
Create a small example of an object
-----1
var r={};
R.name= "Tom";
r.age=18;
-----2
var r={name: "Tom", Age:20};//json object
alert (r.age);
---1,2 is equivalent.
The pattern of-------prototype
----1
function person () {};
Person.prototype.name= "Chinese";
person.prototype.age=20;
Abbreviated form of the prototype pattern--2
function person () {};
Person.prototype={name: "Chinese",
Age:20,}
-----1,2 Equivalence of
//================================
/* {name: "Chinese",
Age:20,}
The above format itself is an object, which is paid to the prototype of another object, making
All properties of another object. is essentially inheritance.
*/
//================================
Standard object Inheritance example, Person,student
Define a Person object
function person () {};
Person.prototype.name= "Chinese";
person.prototype.age=20;
var person=new person ();
Define a Student object
function Student () {};
Student.prototype=person;
Student.prototype.girlfriend= "can have";
var stu=new Student ();
Stu.laop= "Don't fall in Love";
alert (stu.name);//Inheriting from the parent object's instance
alert (STU.LAOP);//Self newly added properties

That defines a Teamleader object.
function Teamleader () {};
Teamleader.prototype=new Student ()//inherited from Student
Teamleader.prototype.teamnum=8;//teamleader Own Properties
To create your own instance
var teamleader=new teamleader ();
alert (teamleader.teamnum);
Teamleader.girlfriend= "also can not have oh";
alert (teamleader.name);
//=================================
The core of inheritance in/*js is prototype*/
//=================================
</script>
<body>

</body>
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.