作家
登录

js模拟类继承小例子

作者: 来源:www.28hudong.com 2013-03-30 01:26:09 阅读 我要评论

复制代码 代码如下: //使用原型继承,中间使用临时对象作为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

  推荐阅读

  js+css在交互上的应用

但灵活应用CSS会有给人眼前一亮的感觉! 以下用一个简单的例子来阐述我想说的。 CSS代码: 复制代码 代码如下: #nav li ul { display:none; } HTML代码: 复制代码 代码如下: <div id="nav"> <ul class=""> <li> >>>详细阅读


本文标题:js模拟类继承小例子

地址:http://www.17bianji.com/kaifa2/JS/25995.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)