Skip to content

Instantly share code, notes, and snippets.

@qubyte
Last active August 29, 2015 14:03
Show Gist options
  • Save qubyte/14dade3929faf0cb6404 to your computer and use it in GitHub Desktop.
Save qubyte/14dade3929faf0cb6404 to your computer and use it in GitHub Desktop.
A quick look at what making objects without using this might look like. I'm particularly interested in keeping methods decoupled so that they can be put into their own modules and easily tested. This leads to a pseudo-this object (called context here) to give methods access to shared data.
// Methods will be bound. This allows them to be public or private
// later on without needing `this`. These can be required in etc.
function addToCounterMixin(context, num) {
context.counter += num;
}
// Use this to proxy a field on from one object to another.
function proxy(context, obj, fieldName) {
Object.defineProperty(obj, fieldName, {
set: function (val) {
context[fieldName] = val;
},
get: function () {
return context[fieldName];
},
enumerable: true
});
}
// This is what replaces a constructor.
function makeObj() {
// Context holds all data that methods may need access to.
var context = {
counter: 0
};
// Bind methods to a context.
var obj = {
addToCounter: addToCounterMixin.bind(null, context)
};
// Get and set counter on internal context. Probably best avoided.
proxy(context, obj, 'counter');
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment