var es = {};

es.extend = function(dist, src) {
  for (var k in src) {
    if (src.hasOwnProperty(k)) {
      dist[k] = src[k];
    }
  }
};

es.inherit = function(Klass, Base) {
  function f() {}
  f.prototype = Base.prototype;
  Klass.prototype = new f;
  Klass.prototype.constructor = Klass;
  Klass.Base = Base;
};

es.create = function(oo) {
  var Klass = oo.init;

  function realBase(fn) {
    var count = 0;
    function realBase() {
      var Base = Klass.Base, i = 0;
      while(count !== i) {
        Base = Base.Base;
        i++;
      }
      count++;
      fn.call(this, Base, arguments);
      count--;
    }
    return realBase;
  }


  oo.Base = realBase(function(Base, argv) {
    Base.apply(this, argv);
  });

  oo.oo = realBase(function(Base, argv) {
    Base.prototype[argv[0]].apply(this, [].slice.call(argv, 1));
  });


  Klass.prototype = oo;

  Klass.extend = function(Base) {
    var Klass = this;
    var old = Klass.prototype;
    es.inherit(Klass, Base);//Klass重新挂载原型
    es.extend(Klass.prototype, old); //将之前的原型合并进去
    return Klass;
  };
  
  return Klass;
};



/////////////////////test////////////////

var People = es.create({
  init: function(name) {
    this.name = name;
  },
  intro: function() {
    console.log('I am ' + this.name);
  }
});

var Student = es.create({
  intro: function() {
    this.oo('intro');//调用父类方法
    console.log('I am learning ' + this.lesson);
  },
  init: function(name, lesson) {
    this.Base(name);
    this.lesson = lesson;
  }
}).extend(People);



var Son = es.create({
  init: function(name, lesson, age) {
    this.Base(name, lesson);//调用父类构造函数
    this.age = age;
  },
  intro: function() {
    this.oo('intro');
    console.log('I am ' + this.age + ' years old');
  }
}).extend(Student);



var p = new People('eric');
p.intro();

var s = new Student('eric', 'js')
s.intro();

var son = new Son('eric', 'js', 34);
son.intro();

erichooooow
229 声望5 粉丝

simple is not easy