Created
March 28, 2012 12:15
-
-
Save nakamura-to/2225739 to your computer and use it in GitHub Desktop.
private members using Function.prototype.bind
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
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