您的位置:首页 > Web前端 > JavaScript

js的继承实现方式

2008-08-27 21:13 861 查看
第一种 prototype 引用型原型继承
语言支持:js原生支持的继承方式 构造器的的prototype属性作为类的原型 每个该类的对象都持有一个到原型的引用 当对象中的属性不存在时 可以访问原型的属性
代码示例:
<script>
function parent(){
this.x=10;
}
function child(){
}
child.prototype=new parent();
var childObj=new child();
alert(childObj.x);
</script>


第二种 复制型原型继承
语言支持:js new运算符的性质 当构造函数return值为非空对象时 new表达式返回return的对象
代码示例:
<script>
function parent(){
this.x=10;
}
function child(){
var ret=new parent();
ret.y=20;
return ret;
}

var childObj=new child();
alert(childObj.x);</script>


第三种 类继承 属性抄写
语言支持:for in枚举对象所有属性
代码:
<script>
function parent(){
this.x=10;
}
function child(){
var parentObj=new parent();
for(var p in parentObj)this[p]=parentObj[p];
}
var childObj=new child();
alert(childObj.x);</script>


第四种 类继承 对象冒充
语言支持: 1.动态添加和删除方法 2.函数的call和apply
代码:
用语言支持1实现的类继承
<script>
function parent(){
this.x=10;
}
function child(){
this.parent=parent;
this.parent();
delete this.parent;
}
var childObj=new child();
alert(childObj.x);</script>

用语言支持2实现的类继承
<script>
function parent(){
this.x=10;
}
function child(){
parent.call(this);
}
var childObj=new child();
alert(childObj.x);</script>

第五种 原型抄写
语言支持:通过修改类的原型对象 可以为一类对象添加属性和方法
代码:
<script>
function parent(){}
parent.prototype.me=function(){alert("parent")};
function child(){}
for(var p in parent.prototype)child.prototype[p]=parent.prototype[p];
var childObj=new child();
childObj.me();</script>


第六种 元类
语言支持: js函数都是对象 且js函数可被构造
代码:
<script>function parent(string){
var child=new Function("this.x=10;"+string);
return child;
}
var child=new parent("this.y=20;");

var childObj=new child();
alert(childObj.y);
</script>


以下通过混合构造函数与原型方式来实现JS的继承功能。 Polygon为父类,Triangle Rectangle 为子类。
function Polygon (iSiders){
this.sides = iSiders;
}
Polygon.prototype.getArea = function(){
return 0;
}

function Triangle(iBase,iHeight){
Polygon.call(this,3);
this.base = iBase;
this.height = iHeight;
}
Triangle.prototype = new Polygon();
Triangle.prototype.getArea = function(){
return 0.5*this.base*this.height;
}

function Rectangle(iLength,iWidth){
Polygon.call(this,4);
this.length = iLength;
this.width = iWidth;
}
Rectangle.prototype = new Polygon();
Rectangle.prototype.getArea = function(){
return this.length*this.width;
}
var triangle = new Triangle(12,4);
var rectangle = new Rectangle(22,10);
alert(triangle.getArea);
alert(rectangle.getArea);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: