UNPKG

1.22 kBJavaScriptView Raw
1const _ = require('lodash');
2
3// Uses a hash of prototype properties and class properties to be extended.
4module.exports = function extend(protoProps, staticProps) {
5 const Parent = this;
6
7 // The constructor function for the new subclass is either defined by you
8 // (the "constructor" property in your `extend` definition), or defaulted
9 // by us to simply call the parent's constructor.
10 const Child =
11 protoProps && protoProps.hasOwnProperty('constructor')
12 ? protoProps.constructor
13 : function() {
14 return Parent.apply(this, arguments);
15 };
16
17 Object.assign(Child, Parent, staticProps);
18
19 // Set the prototype chain to inherit from `Parent`.
20 Child.prototype = Object.create(Parent.prototype, {
21 constructor: {
22 value: Child,
23 enumerable: false,
24 writable: true,
25 configurable: true
26 }
27 });
28
29 if (protoProps) {
30 Object.assign(Child.prototype, protoProps);
31 }
32
33 // Give child access to the parent prototype as part of "super"
34 Child.__super__ = Parent.prototype;
35
36 // If there is an "extended" function set on the parent,
37 // call it with the extended child object.
38 if (_.isFunction(Parent.extended)) Parent.extended(Child);
39
40 return Child;
41};