本文通过具体代码示例,解析 JavaScript 中面向对象编程的核心实现方式。重点介绍如何利用 ClassModel 创建类模型,通过 extend 函数实现对象成员的复制与继承,并演示子类如何重写父类方法以实现多态行为。
}
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");