免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 16778 | 回复: 0
打印 上一主题 下一主题

[JavaScript] js四种继承方式 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2016-03-05 00:08 |只看该作者 |倒序浏览
js是一个很自由的语言,没有强类型的语言的那种限制,实现一个功能往往有很多做法。继承就是其中的一个,在js中继承大概可以分为四大类,下面开始详细说说js的继承。

1、原型继承

function funcA(){
    this.show=function(){
        console.log("hello");
    }
}
function funcB(){

}
funcB.prototype=new funcA();
var b=new funcB();
b.show();
这里是运用原型链的特性实现,缺点很明显,如果继承的层次比较多的话,修改顶层的原型的方法,会对下面所有的对象产生影响。

2、原型冒充:

function funcA(age){
    this.name="xiaoxiao";
    this.age=age;
    this.show=function(){
        console.log(this.name+this.age)

    }
}
function funcB(){
    this.parent=funcA;
    this.parent(40);
    delete this.parent;

}
var b=new funcB();
b.show();
这个继承的方法就是把funcA中的代码全部拿到funcB中执行一下,可以解释成:

function funcA(age){
    this.name="xiaoxiao";
    this.age=age;
    this.show=function(){
        console.log(this.name+this.age)

    }
}
function funcB(){
    // this.parent=funcA;
    // this.parent(40);
    // delete this.parent;
         //其实上面的过程只不过是把funcA搬过来
    this.name="xiaoxiao";
    this.age=age;
    this.show=function(){
        console.log(this.name+this.age)

    }

}
var b=new funcB();
b.show();
3、call和apply

function funcA() {
    this.show = function(str) {
        console.log(str);
    }
}
function funcB() {
    this.read = function() {}
}
var a = new funcA();
var b = new funcB();
funcA.call(b);//use call
a.show("a");
b.show("b");
call和apply效果是一样的,不过是传参方式上不一样,但是推荐用call,因为apply的效率会低很多。

4、复制继承

function funcA(){
    this.name="hello";
    this.show=function(){
        console.log(this.name);
    }
}
function funcB(){
    this.extend=function(o){
        for(var p in o){
            this[p]=o[p];
        }
    }
}
var a=new funcA();
var b=new funcB();
b.extend(a);
b.show();
这个类似于jquery的extend的方法,原理是把a中的属性遍历到b中。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP