zoukankan      html  css  js  c++  java
  • 使用js模拟类继承小例子

    代码
    Function.prototype.method = function (name, func) {
        
    if (!this.prototype[name]) {
            
    this.prototype[name] = func;
        }
        
    return this;
    };
    var extend = function (subType, superType) {
        
    //创建临时对象,临时对象的原型指针指向父类型原型,并让子类型原型对象指向临时对象。从而通过原型链继承父类型共享方法和属性
        function F() { };
        F.prototype 
    = superType.prototype;
        subType.prototype 
    = new F();

        
    //重新设置子类型原型对象constuctor属性,已支持正确的instanceof操作符类查询对象的正确类型
        subType.prototype.constructor = subType; 
        
    //设置子类型base属性为父类型,方便借用构造函数继承父类型属性
        subType.base = superType;

        
    //检查父类型原型constructor属性是否正确设置,如果没有帮它正确设置
        if (superType.prototype.constructor === Object.prototype.constructor) {
            superType.prototype.constructor 
    = superType;
        }

    };

    function Parent(name) {
        
    this.name = name;
    }

    Parent.method(
    "sayHello"function () {
        alert(
    this.name);
    })
    .method(
    "method1",function(){})
    .method(
    "method2",function(){});

    function Child(name, age) {
        Child.base.call(
    this, name);
        
    this.age = age;
    }
    extend(Child, Parent);
    Child.method(
    "sayAge"function () {
        alert(
    this.age);
    })

    var p = new Parent("aa");

    p.sayHello();

    var c = new Child("bb",11);
    c.sayHello();
    c.sayAge();


  • 相关阅读:
    RabbitMQ 安装
    字符串转换
    sqlserver 远程链接
    力软框架 接口映射的时候不能修改添加接口原因
    json串处理2
    版本比较,数据库存储
    各种分页方法推荐
    生成数据库编号重复问题
    从统计局抓取2016年最新的全国区县数据!!
    “集群和负载均衡”等的通俗解释
  • 原文地址:https://www.cnblogs.com/xhan/p/1779096.html
Copyright © 2011-2022 走看看