js中的继承
2015-09-15 17:38
477 查看
js中继承的实现方式很多,此处给出两种常用方式。
<!DOCTYPE html> <html> <head> <meta charset='UTF-8'> <title></title> </head> <body> </body> <script type="text/javascript"> //Range构造函数,定义属性 function Range(from,to){ this.from = from; this.to = to; } //Range原型,定义方法 Range.prototype.isIn = function(num){ if(num>=this.from&&num<=this.to){ return true; } return false; } //Range原型中也可以定义有固定值的属性 Range.prototype.func = '范围'; //SubRange构造函数,定义属性 function SubRange(from,to){ Range.call(this,from,to); this.middle = (from+to)/2; } /* //方法一。需建立Range的实例 SubRange.prototype = new Range();//此处是与方法二的区别 SubRange.prototype.constructor = SubRange; */ //方法二。通过空对象作中介,让SubRange继承Range.prototype,这样做的优点是效率比较高(不用执行和建立Range的实例了),比较省内存。 extend(SubRange,Range); function extend(Child, Parent) { //此处是与方法一的区别 var F = function(){}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; //Child.uber = Parent.prototype;//本行只是为了实现继承的完备性,纯属备用性质。 } //新增方法 SubRange.prototype.isLagger = function(num){ if(!this.isIn(num)&&num>this.to) { return true; } return false; }; //重写方法 SubRange.prototype.isIn = function(num){ if(num>this.from&&num<this.to) { return true; } return false; }; var subRange = new SubRange(1,10); alert(subRange.isIn(1)); alert(subRange.isLagger(3)); alert(subRange.func); var range = new Range(1,10); alert(range.isIn(1)); alert(range.func); </script> </html>
相关文章推荐
- js 判断两个标准时间是不是同一周
- javascript数据缓存
- 网页加载效果(利用图片加载)
- js控制只允许输入数字
- Javascript中this关键字详解
- Cookies vs Tokens. Getting auth right with Angular.JS
- js+flash实现,单击按钮复制文本框内容
- JSTL标签库 fmt标签
- video js Tracks
- JS监听键盘两个组合键触发的事件
- 深入理解Javascript之this关键字
- 深入理解JavaScript中的this关键字
- JSTL函数标签库 fn标签
- video js选项
- js中的prototype
- 修复IE9.0下PlaceHolder 属性问题js脚本
- 贝塞尔曲线的计算方式与js计算
- JSP 中九大内置对象和四大作用域
- video js安装
- easyloader.js源代码分析