`
zhufeng1981
  • 浏览: 71630 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

JS继承的几种方式

阅读更多

关于Js继承的几种方式,总结一下,以便查看。

 

第一种 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
代码示例:

<script>
function parent(){
    this.x=10;
}
function child(){
    this.parent=parent;
    this.parent();
    delete this.parent;
}
var childObj=new child();
alert(childObj.x);
</script>
 
<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>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics