this in this context will be the same. The only thing you lose is myVal . You are right that you cannot use Function.bind , because it does not allow you to specify in order to preserve the original (call time) this
Here you can pass myVal and keep the same this using a modified version of Function.bind that we call myBind
function myBind(fun, context, customArgs, index) { return function() {
To demonstrate the flexibility of this function, let us associate more than one argument and you need to insert it at the beginning of the call time arguments
function Save() { var myVal = 3.14, val2 = 6.28; // some arbitrary values $('#myID').each( // myFunction wil be called with myVal and val2 as its first parameter myBind(myFunction, null, [myVal, val2], 0); ); } // Since I don't need element, it already available as this, we don't // declare the element parameter here function myFunction(myVal, val2, index) { if ($(this).val() === myVal || $(this.val() === val2)) { // do it here } }
This is almost the same answer as Samuel Kayieri. The only difference is that we are creating another version of Function.bind that does not bind this , just the arguments. Another advantage of this version is that you can choose where to insert related arguments,
source share