Skip to content

Instantly share code, notes, and snippets.

@bkonkle
Created August 14, 2014 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bkonkle/e69b8ddc04fbac983008 to your computer and use it in GitHub Desktop.
Save bkonkle/e69b8ddc04fbac983008 to your computer and use it in GitHub Desktop.
/*
* Backbone's extend functionality, which is almost identical to CoffeeScript's
* method. This will make it easy to extend classes originally created in
* CoffeeScript.
*
* From: https://github.com/jashkenas/backbone/blob/c33dcdeffd85a5b749100249b8b9de7be44a0594/backbone.js#L1648
*/
'use strict';
var _ = require('underscore');
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
// Add static properties to the constructor function, if supplied.
_.extend(child, parent, staticProps);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate();
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) _.extend(child.prototype, protoProps);
// Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
};
module.exports = extend;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment