网络编程 
首页 > 网络编程 > 浏览文章

js模拟类继承小例子

(编辑:jimmy 日期: 2025/5/11 浏览:3 次 )
复制代码 代码如下:
//使用原型继承,中间使用临时对象作为Child的原型属性,临时对象的原型属性再指向父类的原型,
//防止所有子类和父类原型属性都指向通一个对象.
//这样当修改子类的原型属性,就不会影响其他子类和父类
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.base = Parent.prototype;
}

function Parent(name)
{
this.aa = 123;
this.getName = function() {return name;}; //使用闭包模拟私有成员
this.setName = function(value){name=value;};
}
Parent.prototype.print = function(){alert("print!");};
Parent.prototype.hello = function()
{
alert(this.getName() + "Parent")
};

function Child(name,age)
{
Parent.apply(this, arguments);//调用父类构造函数来继承父类定义的属性
this.age = age;
}
extend(Child,Parent); //继承Parent

Child.prototype.hello = function() //重写父类hello方法
{
alert(this.getName() + "Child");

Parent.prototype.hello.apply(this,arguments); //调用父类同名方法
};
//子类方法
Child.prototype.doSomething = function(){ alert(this.age + "Child doSomething"); };

var p1 = new Child("xhan",22);

var p2 = new Child("xxx",33);

p1.hello();
p2.hello();

p1.doSomething(); //子类方法
p1.print(); //父类方法

alert(p1 instanceof Child); //true
alert(p1 instanceof Parent);//true
上一篇:IE6,IE7下js动态加载图片不显示错误
下一篇:javascript 循环读取JSON数据的代码
一句话新闻
Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 网站地图 SiteMap