Created
August 5, 2011 21:42
-
-
Save tj/1128588 to your computer and use it in GitHub Desktop.
lame js String#prototype helpers
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 User(name) { | |
this.name = name; | |
} | |
User.prototype.toString = function(){ | |
return '<User ' + this.name + '>'; | |
}; | |
User.prototype.may = function(perm){ | |
return false; | |
}; | |
function Admin(name) { | |
User.call(this, name); | |
} | |
Admin.prototype.__proto__ = User.prototype; | |
Admin.prototype.may = function(perm){ | |
return true; | |
}; | |
var users = [ | |
new User('tj') | |
, new Admin('tobi') | |
, new User('loki') | |
]; | |
String.prototype.__defineGetter__('prop', function(){ | |
var self = this; | |
return function(obj){ | |
return obj[self]; | |
} | |
}); | |
String.prototype.call = function(){ | |
var self = this | |
, args = arguments; | |
return function(obj){ | |
return obj[self].apply(obj, args); | |
} | |
}; | |
console.log(users.map('name'.prop)); | |
// => ['tj', 'tobi', 'loki'] | |
console.log(users.map('toString'.call())); | |
// => [ '<User tj>', '<User tobi>', '<User loki>' ] | |
console.log(users.filter('may'.call('delete users'))); | |
// => [ <User tobi>' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment