this
在这种情况下将是相同的。您无法访问的一件事是myVal
. 你是对的,你不能使用Function.bind
,因为那不允许你指定保留原件(通话时间)this
以下是您可以使用修改后的版本来传递myVal
和保持不变的方法,我们称之为this
Function.bind
myBind
/**
* Binds the given function to the given context and arguments.
*
* @param {function} fun The function to be bound
* @param {object} context What to use as `this`, defaults
* to the call time `this`
* @param {object[]} customArgs Custom args to be inserted into the call
* @param {number} index Where to insert the arguments in relationship
* to the call time arguments, negative numbers count from the end.
That is, -1 to insert at the end. Defaults to a 0 (beginning of list).
*
*/
function myBind(fun, context, customArgs, index) {
return function() {
// Default the index
index = index || 0;
// Create the arguments to be passed, using an old trick
// to make arguments be a real array
var newArgs = Array.prototype.slice.call(arguments, 0);
// Tack the customArgs to the call time args where the user requested
var spliceArgs = [index, 0].concat(customArgs);
newArgs.splice.apply(newArgs, spliceArgs);
// Finally, make that call
return fun.apply(context || this, newArgs);
}
}
function Save() {
myVal = 3.14 // some arbitrary value
$('#myID').each(
// myFunction wil be called with myVal as its last parameter
myBind(myFunction, null, [myVal], -1)
);
}
function myFunction(index, element, myVal) {
if ($(this).val() === myVal) {
// do it here
}
}
为了演示这个函数的灵活性,让我们绑定多个参数,它应该插入到调用时参数的开头
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's 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
}
}
这与 Samuel Caillerie 的答案几乎相同。唯一的区别是我们创建了一个不同的版本,Function.bind
它不绑定this
,只是参数。此版本的另一个好处是您可以选择插入绑定参数的位置;