javascript 面向对象思想 附源码


复制代码 代码如下:

<html>
<head>
<script type="text/javascript"><!--
ClassModel = //类模型,用于创建类
{
create: function()
{
return function(){this.construct.apply(this,arguments);}
}
}
Extend = function(desc, src) //模拟类继承, 将一个对象的所有成员 复制到 另一个对象中
{
for(var c in src)
{
desc[c] = src[c];
}
return desc;
}
Object.prototype.extend = function(src)
{
return Extend.apply(this, [this, src]);
}
var human = ClassModel.create();
human.prototype =
{
construct : function() //构造函数
{
//alert("construct method");
//alert(this.speak() + "," + this.sleep());
},
speak : function()
{
alert("speak");
},
sleep : function()
{
alert("sleep");
},
sex : function()
{
alert("女");
}
}
var h = new human();
h.speak(); //调用human类的speak方法
var student = ClassModel.create();
student.prototype = (new human()).extend({ //student类继承类human类
sex : function() //方法重载 (多态)
{
alert("男");
},
study : function()
{
alert("studying");
},
thinking : function()
{
alert("thinking");
}


});
var student = new student();
student.sleep(); //调用 父类(human) 的sleep方法
student.study(); //调用 student的study方法
student.thinking(); //调用 student的thinking方法
student.sex(); //结果为 男 不再是父类的 女

// --></script>
</head>
</html>

« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3