Skip to content

Instantly share code, notes, and snippets.

@dherman
Created July 28, 2012 18:08
Show Gist options
  • Save dherman/3194222 to your computer and use it in GitHub Desktop.
Save dherman/3194222 to your computer and use it in GitHub Desktop.
Convert methods to unselfish functions
Function.prototype.unselfish = (function(Fp, Ap) {
var applyMethod = Fp.apply,
callMethod = Fp.call;
var apply = callMethod.bind(applyMethod),
call = callMethod.bind(callMethod);
var sliceMethod = Ap.slice;
return function unselfish() {
var f = this;
return function(self) {
return apply(f, self, call(sliceMethod, arguments, 1));
};
};
})(Function.prototype, Array.prototype);
var hasOwn = Object.prototype.hasOwnProperty.unselfish();
console.log(hasOwn({}, "toString")); // false
console.log(hasOwn({foo:1}, "foo")); // true
@dherman
Copy link
Author

dherman commented Jul 28, 2012

Or maybe I should call it Function.prototype.selfless.

Dave

@medikoo
Copy link

medikoo commented Jul 29, 2012

Why, not:

var hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty);

Dedicated method would still be handy, but then it can be just one line:

var call = Function.prototype.call;
Function.prototype.unselfish = function () {
  return call.bind(this);
};

@dherman
Copy link
Author

dherman commented Jul 29, 2012

I'm writing in a "paranoid style", where as long as the library is initialized before any untrusted code, it will continue to work properly no matter how much someone trashes the standard libraries. Notice how your version calls call.bind, which could break if someone modifies Function.prototype.bind or call.__proto__.

For most applications this probably doesn't matter, but I was just playing around with just how "high-integrity" an implementation you can write.

Dave

@medikoo
Copy link

medikoo commented Jul 29, 2012

I get it, thanks for clarification, good tip.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment