Skip to content

Instantly share code, notes, and snippets.

@safizn
Created November 15, 2018 14:22
Show Gist options
  • Save safizn/cf1ef39f7effd89c0168ebcd76ef9a5b to your computer and use it in GitHub Desktop.
Save safizn/cf1ef39f7effd89c0168ebcd76ef9a5b to your computer and use it in GitHub Desktop.
// https://www.accelebrate.com/blog/javascript-es6-classes-and-prototype-inheritance-part-1-of-2/
// the extends function is not already defined within the current
// context; therefore, define it
export function extendClass({ childClass, parentClass }) {
// mixin pattern for copying parent constructor function properties
// as static properties to the child constructor function
// properties on constructor function are commonly known as static
// properties
for (var parentPropertyName in parentClass) {
// only copy properties specifically defined on the parent
if (parentClass.hasOwnProperty(parentPropertyName)) {
// for primitive types, this will copy the value,
// for object types, this will copy the reference only
childClass[parentPropertyName] = parentClass[parentPropertyName];
}
}
// constructor function for the object that instantiated child objects
// will inherit from
// this function is unique within the context of each call to extend
function __() {
Object.defineProperty(this, 'constructor', { value: childClass }) // this.constructor = childClass;
}
if (parentClass === null) {
// objects instantiated with the child constructor function will
// inherit from an object that inherits from nothing, not even
// the built-in JavaScript Object
childClass.prototype = Object.create(parentClass);
} else {
// assign the prototype property of the parent constructor function
// to the prototype property of the constructor function defined
// above
__.prototype = parentClass.prototype;
// create the object that all instances of the child will inherit
// from, and assign it to the prototype property of the child
// constructor function
childClass.prototype = new __();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment