Skip to content

Instantly share code, notes, and snippets.

@ronaldronson
Last active January 3, 2016 02:39
Show Gist options
  • Save ronaldronson/8396937 to your computer and use it in GitHub Desktop.
Save ronaldronson/8396937 to your computer and use it in GitHub Desktop.
Own realization of functions bind call and apply.
/** Bind: */
Function.prototype.c_bind = function (cnt) {
var pArgs = [].slice.call(arguments, 0), fn = this;
return function () {
var args = [].slice.call(arguments, 0);
[].splice.apply(pArgs, [0, args.length].concat(args));
return fn.apply(cnt, args);
}
};
/** Apply: */
Function.prototype.c_apply = function (obj, args) {
var toSource = function (val) {
return "function" == typeof val ? val.toString() : val
};
args = args
.map(toSource)
.map(JSON.stringify)
.join(',');
obj = Object(obj);
obj.fn = this;
return new Function ("obj", "return obj.fn(" + args + ")")(obj);
};
/** Call: */
Function.prototype.c_call = function () {
var args = [].slice.call(arguments, 1),
obj = arguments[0],
toSource = function (val) {
return "function" == typeof val ? val.toString() : val
};
args = args
.map(toSource)
.map(JSON.stringify)
.join(',');
obj = Object(obj);
obj.fn = this;
return new Function ("obj", "return obj.fn(" + args + ")")(obj);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment