Javascript继承

<script type="text/javascript">
//继承构造以外的属性和方法
Function.prototype.getExtends = function(){
    if(arguments.length>0){
        for(var ptt in arguments[0]){
            if(ptt=="prototype") continue;
            this.prototype[ptt] = arguments[0][ptt];
        }
    }
}

//继承原型
Function.prototype.getPrototype = function(){
    var p = function(){};
    p.prototype = this.prototype;
    p.getExtends(this);
    return new p;
}

var A = function(txt){
    this.txt = txt;
}
A.color = "black";
A.size = "12px";
A.prototype.bgcolor = "white";
A.show = function(){
      document.write("继承方法:"+this.txt);
}

var B = function(){
    //继承原型
    var p = A.getPrototype();
    //继承构造
    A.apply(p,arguments);
    return p;
}

var c = new B("hello world");

document.write("继承构造:"+c.txt+",继承属性:"+c.color+",继承属性:"+c.size+",继承原型:"+c.bgcolor+"<br/>");

c.show();
</script>



评论: 0 | 引用: 0 | 查看次数: 1774
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 关闭 | [img]标签 关闭