JavaScript 面向对象编程基础:类定义与继承实现
作者:半夏时间:2026-10-23 19:36:48浏览:485
本文通过具体代码示例,解析 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");作者最新文章
JavaScript闭包与类(Class)的区别及适用场景对比
2026-11-05 15:48:57
JavaScript入门要学ES6吗?let与箭头函数等新特性解析
2026-11-05 14:49:16
JavaScript 8种数据类型详解:基本类型与引用类型的区别
2026-11-05 14:25:15
怎么在JavaScript中使用async/await优化Ajax异步流程
2026-11-05 13:56:15
JavaScript replace回调函数实现动态正则替换逻辑
2026-11-05 13:52:13
