欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JS仿Base.js实现的继承示例

程序员文章站 2022-04-10 11:45:21
本文实例讲述了js仿base.js实现的继承。分享给大家供大家参考,具体如下: var klass = function() {}; klass.extendc...

本文实例讲述了js仿base.js实现的继承。分享给大家供大家参考,具体如下:

var klass = function() {};
klass.extendclass = (function() {
  var f = function() {};
  return function(c, p) {
    f.prototype = p.prototype;
    c.prototype = new f();
    c.uper = p.prototype;
    c.prototype.constructor = c;
  };
})();
klass.extend = function(props) {
  var _slice = array.prototype.slice;
  var glass = function() {
    /*if (glass.uper && glass.uper.hasownproperty("init")) {
      glass.uper.init.apply(this, _slice.call(arguments))
    }*/
    if (glass.prototype.hasownproperty("init")) {
      glass.prototype.init.apply(this, _slice.call(arguments));
    }
  };
  klass.extendclass(glass, this);
  glass.extend = this.extend;
  for (var key in props) {
    if (props.hasownproperty(key)) {
      glass.prototype[key] = props[key];
    }
  }
  return glass;
};

example:

var a = klass.extend({
    init: function(name) {
      this.name = name;
      console.log('a constructor is running!');
    },
    getname: function() {
      return this.name;
    }
});
var b = a.extend({
    init: function(name) {
      this.name = name;
      console.log('b constructor is running!');
    },
    getname: function() {
      return this.name;
    },
    a: 'b'
});
var c = b.extend({
    init: function(name) {
      console.log('c constructor is running!');
    },
    c: 'c',
    getname: function() {
      var name = c.uper.getname.call(this);
      return 'hi, i\'m' + this.name;
    }
});
var c1 = new c('zlf');
console.log(c1.getname());

更多关于javascript相关内容感兴趣的读者可查看本站专题:《javascript面向对象入门教程》、《javascript错误与调试技巧总结》、《javascript数据结构与算法技巧总结》、《javascript遍历算法与技巧总结》及《javascript数学运算用法总结

希望本文所述对大家javascript程序设计有所帮助。