Javascript中对象继承的实现小例
更新时间:2014年05月12日 09:47:24 作者:
这篇文章主要介绍了Javascript中对象继承的实现,需要的朋友可以参考下
复制代码 代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
/**
* json对象的格式
{key:value,key:value,key:value..}
*/
//创建对象的小例子
//-----1
var r={};
r.name="tom";
r.age=18;
//-----2
var r={name:"tom",age:20};//json对象
alert(r.age);
//---1,2是等价的
//-------原型模式的写法
//----1
function Person(){};
Person.prototype.name="中国人";
Person.prototype.age=20;
//原型模式的简写形式--2
function Person(){};
Person.prototype={name:"中国人",
age:20,}
//-----1,2等价的
//================================
/* {name:"中国人",
age:20,}
上面的这种格式本身就是个对象,将其付给另一个对象的prototype,就使得
另一个对象的所有属性。实质上就是继承
*/
//================================
//标准的对象继承例子,Person,Student
//定义一个Person对象
function Person(){};
Person.prototype.name="中国人";
Person.prototype.age=20;
var person=new Person();
//定义一个Student对象
function Student(){};
Student.prototype=person;
Student.prototype.girlFriend="可以有的";
var stu=new Student();
stu.laop="不许谈恋爱";
alert(stu.name);//继承自父对象的实例
alert(stu.laop);//自己新添加的属性
//定义一个Teamleader对象的
function Teamleader(){};
Teamleader.prototype=new Student();//继承自Student
Teamleader.prototype.teamNum=8;//Teamleader自己的属性
//创建自己的实例
var teamleader=new Teamleader();
alert(teamleader.teamNum);
teamleader.girlFriend="也不可以有哦";
alert(teamleader.name);
//=================================
/*js中继承的核心就是prototype*/
//=================================
</script>
</head>
<body>
</body>
</html>
相关文章
Openlayers+EasyUI Tree动态实现图层控制
这篇文章主要为大家详细介绍了Openlayers+EasyUI Tree动态实现图层控制,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2020-09-09解决select2在bootstrap modal中不能正常使用的问题
今天小编就为大家分享一篇解决select2在bootstrap modal中不能正常使用的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2018-08-08
最新评论