js模拟实现继承功能

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
<script type="text/javascript">
    //js中模拟继承效果的案例
    //函数对象中的三种“继承” 方式 汇总

    //方式一
//*******************************************************************************************************************
/*    function A() {
    }
    A.prototype = {
        aname:"123",
        method1:function() {
           alert("对象A的原型");
        }
    }
    function B() {
//        this.name="bbb",
//
//        this.method2=function() {
//            alert("对象B的原型");
//        }
    }
    B.prototype = {
        bname:"bbb",
            method2:function() {
        alert("对象B的原型");
    }
    }

    var a = new A();

    B.prototype = a;
    var b = new B();*/

//    b.method2();  //会被a中的原型覆盖 b中的原型,除非逐个添加原型的方式
//    b.method

//    alert(b.bname);

//*********************************************************************************************************************
    //方式二+方式三 解决覆盖问题
    function A(){}
    A.prototype = {
        aname:"aaa",
        method1:function() {
            alert("A的原型对象");
        }
    }
    function B(){}
    //B的原型属性指向A的原型属性
    B.prototype = A.prototype;

    //利用原型分散的添加方式给函数对象B添加属性和方法
    B.prototype.bname = "bbb";
    B.prototype.method2 = function(){
        alert("B的原型对象");
    }

    //分别创建A和B函数对象的小对象
     var  a  = new A();
     var  b = new B();
    a.method2();  //说明a可以访问B的内容
    b.method1();  //说明b也可以访问A的内容

    //因为A的原型指向的新的内存地址,和B原型也指向这个内存地址
    //且后来往原型中添加的属性和方法也是在这个内存地址,共用了一个内存地址:深复制
    //所以模拟实现了继承的功能,但并不是真正的继承

</script>
</head>

<body>

</body>
</html>

 

posted on 2015-09-30 12:15  freedom's_blog  阅读(267)  评论(0编辑  收藏  举报

导航