码迷,mamicode.com
首页 > 编程语言 > 详细

javascript练习-定义子类

时间:2015-12-17 23:52:18      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

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); }

 

javascript练习-定义子类

标签:

原文地址:http://www.cnblogs.com/zjtTT/p/5055616.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!