Last active
January 3, 2016 02:39
-
-
Save ronaldronson/8396937 to your computer and use it in GitHub Desktop.
Own realization of functions bind call and apply.
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
/** 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