Re: javascript中基于原型法直接实现继承中的一个陷阱和解决

本文通过一个具体的JavaScript代码示例,展示了如何使用原型继承的方式创建基类和子类,并实现方法覆盖和扩展。具体包括:定义基类Base及其初始化方法和属性,创建子类Child并继承Base的属性与方法,同时对基类的方法进行扩展。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[code]<SCRIPT LANGUAGE="JavaScript">
<!--
var Class = {
isPrototype: function () {},
create: function() {
return function() {
if (arguments && arguments[0] != Class.isPrototype)
this.initialize.apply(this, arguments);
}
},
extend : function(destination, source) {
for (property in source) {
destination[property] = source[property];
}
return destination;
},
inherit: function () {
var superClass = arguments[0];
var proto = new superClass(Class.isPrototype);
for (var i = 1; i < arguments.length; i++) {
if (typeof arguments[i] == "function") {
var mixin = arguments[i];
arguments[i] = new mixin(OpenLayers.Class.isPrototype);
}
Class.extend(proto, arguments[i]);

if((arguments[i].hasOwnProperty && arguments[i].hasOwnProperty('toString')) ||
(!arguments[i].hasOwnProperty && arguments[i].toString)) {
proto.toString = arguments[i].toString;
}
}
return proto;
}
};
var Base=Class.create();
Base.prototype={
x : 1,
y : 2,
initialize : function(){
this.x=100;
this.y=10;
},
area : function(){
return this.x * this.y
}
}

var Child = Class.create();
Child.prototype=Class.inherit(Base,{
initialize : function(){
Base.prototype.initialize.apply(this);
this.x=10;
},
area : function(){
var old=Base.prototype.area.apply(this);
return old + 100000;
}
});
var base=new Base();
var child=new Child();
alert(child.area())
//-->
</SCRIPT>[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值