legacy-extends
Version:
Helper to extend a class including defining super_ and superConstruct (optional) on the derived class. Compatible with Node.js inherits and handles es6 classes using Reflect API
48 lines (47 loc) • 2.01 kB
JavaScript
function ensureProperties(names, self, args) {
if (self[names[0]] !== args[0]) {
const length = names.length;
for(let index = 0; index < length; index++){
self[names[index]] = args[index];
}
}
}
const hasProp = {}.hasOwnProperty;
function extendLegacy(child_, parent_, options) {
const child = child_;
const parent = parent_;
const initialize = options && options.ensureProperties && options.ensureProperties.length ? ensureProperties.bind(null, options.ensureProperties) : null;
for(const key in parent){
if (hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.prototype.constructor = child;
const khild = child;
khild.super_ = parent.prototype;
khild.superConstruct = function construct() {
// biome-ignore lint/complexity/noArguments: Apply arguments
parent.prototype.constructor.apply(this, arguments);
// biome-ignore lint/complexity/noArguments: Apply arguments
!initialize || initialize(this, arguments);
return this;
};
}
function extendReflect(child_, parent_, options) {
const child = child_;
const parent = parent_;
const initialize = options && options.ensureProperties && options.ensureProperties.length ? ensureProperties.bind(null, options.ensureProperties) : null;
Reflect.setPrototypeOf(child.prototype, parent.prototype);
Reflect.setPrototypeOf(child, parent);
const khild = child;
khild.super_ = parent.prototype;
khild.superConstruct = function construct() {
// biome-ignore lint/complexity/noArguments: Apply arguments
const self = Reflect.construct(parent, arguments, child);
// biome-ignore lint/complexity/noArguments: Apply arguments
!initialize || initialize(self, arguments);
return self;
};
}
export default typeof Reflect === 'undefined' ? extendLegacy : extendReflect;