Skip to content

Instantly share code, notes, and snippets.

@nakamura-to
Created March 28, 2012 12:15
Show Gist options
  • Save nakamura-to/2225739 to your computer and use it in GitHub Desktop.
Save nakamura-to/2225739 to your computer and use it in GitHub Desktop.
private members using Function.prototype.bind
function create(behaviors, context) {
return Object.getOwnPropertyNames(behaviors).reduce(function(obj, name) {
obj[name] = behaviors[name].bind(context);
return obj;
}, {});
}
var Gadget = {
getName: function () {
return this.name;
},
getColor: function () {
return this.color;
}
};
var toy = create(Gadget, {name: 'iPod', color: 'black'});
console.log(toy.name); // undefined;
console.log(toy.color); // undefined;
console.log(toy.getName()); // iPod
console.log(toy.getColor()); // black
var getName = toy.getName;
console.log(getName()); // iPod
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment