Last active
December 17, 2015 08:59
-
-
Save rohn/5583657 to your computer and use it in GitHub Desktop.
an example of a module pattern, extending another object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var _ = require('underscore'); | |
// an object that we will extend later | |
var foo = { | |
baz: function() { | |
// some interesting behaviour | |
} | |
}; | |
foo.baz.prototype.fubar = function() { | |
// some interesting behaviour | |
}; | |
// make our object (normally this would be in a different .js | |
// file from the object being extended) | |
var be = {}; | |
// add something to our object so we can prove it still has it | |
be.yuck = function() { | |
// insteresting behaviour | |
}; | |
be.something = 'interesting value'; | |
// where the magic begins | |
// first we'll build the thing that is going to be added | |
// into our object, but then before we add it to our | |
// object we'll first extend our first object into this | |
// one. | |
(function(be) { | |
var fubar = (function() { | |
function fubar() { | |
// interesting behaviour | |
} | |
return fubar; | |
})(); | |
be = _.extend(be, foo); | |
be.fubar = fubar; | |
})(be || (be = {})); | |
// and now we can use it | |
be.fubar(); | |
be.yuck(be.something); | |
be.baz(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment