1、inheritprototype.js

;(function(){
    var s = {
        inheritObject:function(o){//对象继承封装
            var F = function(){};
            F.prototype = o;
            return new F();
        },
        inheritPrototype:function(subclass,supperclass){//原型继承封装
            var obj = this.inheritObject(supperclass.prototype);
            obj.constructor = subclass;
            subclass.prototype = obj;
        }
    };
    window.$ = window.s = s;//起别名并把闭包内的命名空间对象s暴露出去
})(window);

2、inheritprototype.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="js/inheritprototype.js"></script>
</head>
<body>

</body>
<script type="text/javascript">
;(function(){
    function Shape(){//超类
        this.name = 'Lucy';
        this.type = '超体者'
    }
    Shape.prototype = {
        init:function(){
            var name = this.getname();
            var type = this.gettype();
            console.log(name);
            console.log(type);
        },
        getname:function(){
            return this.name;
        },
        gettype:function(){
           return this.type;
        }
    }
    function Triangle(){//子类
        Shape.apply(this);//this继承构造体
        this.sex = '女';
    }
    $.inheritPrototype(Triangle,Shape);//这里一定要注意,是先继承再拓展自己的原型方法,否则报错
    Triangle.prototype.getsex = function(){
       console.log(this.sex);
    }
    var o = new Triangle();
    o.init();//继承父元素的init()并执行
    o.getsex();//执行Triangle构造函数的方法
})();
</script>
</html>

posted on 2016-05-17 14:47  杨杨0708  阅读(1795)  评论(0编辑  收藏  举报