Skip to content

Instantly share code, notes, and snippets.

@LeeeeeeM
Created March 10, 2018 02:57
Show Gist options
  • Save LeeeeeeM/78b38c60b4f2c06aecb46bcf34644c7a to your computer and use it in GitHub Desktop.
Save LeeeeeeM/78b38c60b4f2c06aecb46bcf34644c7a to your computer and use it in GitHub Desktop.
javascript extends
var Class = (function () {
initial = false;
// var _mix = function(target, source) {
// for (var k in source) {
// if (!target.hasOwnProperty(k)) {
// target[k] = source[k];
// }
// }
// return target;
// }
var reg = /\b_super\b/;
var _extend = function(props) {
var _super = this.prototype;
initial = true;
var prototype = new this();
initial = false;
// var items = [].slice.call(arguments) || [];
// var item
// while(item = items.shift()) {
// // 支持构造函数
// _mix(prototype, item.prototype || item);
// }
for (var name in props) {
prototype[name] = typeof props[name] === 'function' && typeof prototype[name] === 'function' && reg.test(props[name]) ?
(function(fn, name) {
return function() {
var temp = this._super;
this._super = _super[name];
var ret = fn.apply(this, [].slice.call(arguments));
this._super = temp;
return ret;
}
})(props[name], name) : props[name];
}
function SubClass() {
if (!initial && this.init) {
this.init.apply(this, arguments);
}
}
SubClass.prototype = prototype;
SubClass.extend = _extend;
return SubClass;
}
function Class() {
}
Class.extend = _extend;
return Class;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment