zl程序教程

您现在的位置是:首页 >  前端

当前栏目

Javascript中对象继承的实现小例

JavaScript对象继承 实现 小例
2023-06-13 09:15:26 时间
复制代码代码如下:

<!DOCTYPEhtml>
<html>
<head>
<metacharset="UTF-8">
<title>Inserttitlehere</title>
<scripttype="text/javascript">
/**
*json对象的格式
{key:value,key:value,key:value..}
*/
//创建对象的小例子
//-----1
varr={};
r.name="tom";
r.age=18;
//-----2
varr={name:"tom",age:20};//json对象
alert(r.age);
//---1,2是等价的
//-------原型模式的写法
//----1
functionPerson(){};
Person.prototype.name="中国人";
Person.prototype.age=20;
//原型模式的简写形式--2
functionPerson(){};
Person.prototype={name:"中国人",
age:20,}
//-----1,2等价的
//================================
/*{name:"中国人",
age:20,}
上面的这种格式本身就是个对象,将其付给另一个对象的prototype,就使得
另一个对象的所有属性。实质上就是继承
*/
//================================
//标准的对象继承例子,Person,Student
//定义一个Person对象
functionPerson(){};
Person.prototype.name="中国人";
Person.prototype.age=20;
varperson=newPerson();
//定义一个Student对象
functionStudent(){};
Student.prototype=person;
Student.prototype.girlFriend="可以有的";
varstu=newStudent();
stu.laop="不许谈恋爱";
alert(stu.name);//继承自父对象的实例
alert(stu.laop);//自己新添加的属性

//定义一个Teamleader对象的
functionTeamleader(){};
Teamleader.prototype=newStudent();//继承自Student
Teamleader.prototype.teamNum=8;//Teamleader自己的属性
//创建自己的实例
varteamleader=newTeamleader();
alert(teamleader.teamNum);
teamleader.girlFriend="也不可以有哦";
alert(teamleader.name);
//=================================
/*js中继承的核心就是prototype*/
//=================================
</script>
</head>
<body>

</body>
</html>