Implementation of object inheritance in Javascript

  • 2020-03-30 02:54:53
  • OfStack

 
<!DOCTYPE html> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>Insert title here</title> 
<script type="text/javascript"> 
 
//Small example of creating 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 the same thing
//-- writing method of prototype pattern
//----1 
function Person(){}; 
Person.prototype.name=" The Chinese "; 
Person.prototype.age=20; 
//A shorthand form of the prototype pattern --2
function Person(){}; 
Person.prototype={name:" The Chinese ", 
age:20,} 
//-- -- -- -- -- 1, 2 equivalent
//================================ 
 
//================================ 
//Standard object inheritance examples, Person,Student
//Define a Person object
function Person(){}; 
Person.prototype.name=" The Chinese "; 
Person.prototype.age=20; 
var person=new Person(); 
//Define a Student object
function Student(){}; 
Student.prototype=person; 
Student.prototype.girlFriend=" Can some "; 
var stu=new Student(); 
stu.laop=" Don't fall in love "; 
alert(stu.name);//An instance inherited from the parent object
alert(stu.laop);//Add your own new properties

//Of a Teamleader object
function Teamleader(){}; 
Teamleader.prototype=new Student();//Inherited from the Student
Teamleader.prototype.teamNum=8;//Attributes of the Teamleader himself
//Create your own instance
var teamleader=new Teamleader(); 
alert(teamleader.teamNum); 
teamleader.girlFriend=" There can't be "; 
alert(teamleader.name); 
//================================= 
 
//================================= 
</script> 
</head> 
<body> 

</body> 
</html> 

Related articles: