zoukankan      html  css  js  c++  java
  • javascript练习-定义子类

    function defineSubclass(superclass,  //父类的构造函数
                            constructor,  //新的子类的构造函数
                            methods,      //实例方法:复制至原型中
                            statics)      //类属性:复制至构造函数中
    {
      //建立子类的原型对象
      constructor.prototype = inherit(superclass.prototype);
      constructor.prototype.constructor = constructor;
      //像对常规类一样复制方法和类属性
      if(methods) extend(constructor.prototype,methods);
      if(statics) extend(constructor,statics);
    
      return constructor;
    }
    
    function inherit(p)
    {
      if(!p){throw TypeError();}
      if(Object.create){Object.create(p);}
    
      var t = typeof p;
      if(t !== "object" && t !== "function")
      {
        throw TypeError();
      }
      function f(){};
      f.prototype = p;
      return new f();
    }
    
    function extend(proto,methods)
    {
      proto[methods] = methods();
      return proto;
    }
    
    function Person(name,age){
      this.name = name;
      this.age = age;
    }
    
    Person.prototype.eat = function(){alert("eat!");}
    
    function Student(){}
    
    defineSubclass(Person,Student,function learn(){alert("learn!");})
    //通过父类构造函数的方法来做到这一点

    Function.prototype.extend = function(constructor,methods,statics) { return defineSubclass(this,constructor,methods,statics); }
  • 相关阅读:
    HDU1106 排序
    HDU2050 折线分割平面
    HDU2048 神、上帝以及老天爷
    POJ1836 Alignment
    POJ1182 食物链
    HDU2067 小兔的棋盘
    HTML中的ID不能以数字开头
    automake,autoconf使用详解
    How to install Samba server on Ubuntu 12.04
    Netbeans使用UTF-8编码
  • 原文地址:https://www.cnblogs.com/zjtTT/p/5055616.html
Copyright © 2011-2022 走看看