Last active
April 19, 2025 05:17
-
-
Save branneman/5814160 to your computer and use it in GitHub Desktop.
JavaScript call() vs apply() vs bind() vs $.proxy()
This file contains hidden or 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
var fn = function(arg1, arg2) { | |
var str = '<p>aap ' + this.noot + ' ' + arg1 + ' ' + arg2 + '</p>'; | |
document.body.innerHTML += str; | |
}; | |
var context = { | |
'noot': 'noot' | |
}; | |
var args = ['mies', 'wim']; | |
// Calls a function with a given 'this' value and arguments provided individually. | |
// Support: everywhere | |
fn.call(context, args[0], args[1]); | |
// Calls a function with a given 'this' value and arguments provided as an array | |
// (or an array like object). | |
// Support: everywhere | |
fn.apply(context, args); | |
// Creates a new function that, when called, has its 'this' keyword set to the | |
// provided value, with a given sequence of arguments preceding any provided | |
// when the new function was called. | |
// Support: ECMAScript >= 5 (thus >= IE9) | |
var boundFn1 = fn.bind(context, args[0], args[1]); | |
boundFn1(); | |
// Same as bind() | |
// Support: same as your jQuery version, available since 1.4 | |
var boundFn2 = $.proxy(fn, context, args[0], args[1]); | |
boundFn2(); |
Thank you so much! It really helped!
Thanks for an helpful post
Finally I got it, thanks! XD
Merely a note (for me), to map an array of values as arguments:
fn.bind.apply(fn, [context].concat(args))()
fn.bind.apply(fn, Array.prototype.concat.call(context, args))()
fn.bind.apply(fn, args.slice(0).reverse().concat(context).reverse())()
...any other solutions?
Awesome :)
Thx a lot 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great example