js中的继承
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>