13 November 2017 · JavaScript
Inheritance in JavaScript
// core.js
define([], function() {
var Private = {
objExtend: function(obj) {
var args = Array.prototype.slice.call(arguments, 1);
args.forEach(function (source) {
for (var prop in source) {
if (prop) {
obj[prop] = source[prop];
}
}
});
return obj;
},
extend: function(protoProps, staticProps) {
/*jshint validthis:true */
var parent = this;
var child;
if (protoProps && Object.prototype.hasOwnProperty.call(protoProps, 'constructor')) {
child = protoProps.constructor;
}
else {
child = function () {
parent.apply(this, arguments);
};
}
Private.objExtend(child, parent, staticProps);
var Surrogate = function () {
this.constructor = child;
};
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate();
if (protoProps) {
Private.objExtend(child.prototype, protoProps);
}
child.__super__ = parent.prototype;
return child;
}
};
return Private;
});
// SomeClass.js
define([
'core'
], function (core) {
'use strict';
function SomeClass(attributes, options) {
// constructor
}
function somePrivateFunction() {
// ....
}
SomeClass.prototype = {
somePublicFunction: function() {
// ....
}
}
SomeClass.extend = core.extend;
return SomeClass;
});