我可以通过"this"吗?作为javascript中另一个函数的参数 [英] Can I pass "this" as a parameter to another function in javascript
问题描述
我有这个:
$('#slider li').click(function () {
var stepClicked = $(this).index();
alert(stepClicked);
if (stepClicked != 0) {
$('#cs_previous').removeClass('cs_hideMe');
} else {
$('#cs_previous').addClass('cs_hideMe');
}
$('li.cs_current').removeClass('cs_current');
$($(this)).addClass('cs_current');
moveToNextImage(stepClicked);
function moveToNextImage(stepClicked) {
alert(stepClicked);
var currentIs = $('li.cs_current').index();
var newLeftEdge = currentIs - stepClicked;
$('.cs_riskStageImage').fadeTo(200, .2).animate({
left: newLeftEdge
}, "fast").fadeTo(200, 1);
};
});
警报会显示单击的li的正确索引,并且当我在要调用的最后一个函数moveToNextImage(stepClicked)
中警告变量时,会显示相同的值,但动画不会发生.这可以通过许多其他方式起作用,但是我试图传递单击的列表项的索引值以用于数学计算.
the alert shows the proper index for the li clicked, and when I alert the variable within the last function I'm calling, moveToNextImage(stepClicked)
, the same value shows but the animation isn't happening. This works many other ways, but I'm trying to pass the index value of the list item clicked to use for the math to calculate.
..或者我可以在第一个函数中将值转换为另一个变量,然后再传递给第二个函数吗?
..or can I convert the value to another variable in the first function that I can pass to the second?
推荐答案
javascript函数call()
和apply()
都是出于在上下文中调用函数的目的.
The javascript functions call()
and apply()
are both for precisely for the purpose of calling a function within a context.
function sum() {
return this.num1 + this.num2;
}
function callSum(num1, num2) {
this.num1 = num1
this.num2 = num2
return sum.call(this); //call sum() in the context of this
}
alert(callSum(10, 15));
function applySum(num1, num2) {
this.num1 = num1
this.num2 = num2
return sum.apply(this); //call sum() in the context of this
}
alert(applySum(30, 45));
现在sum()
函数中的this
关键字具有与callSum()
和applySum()
函数中相同的上下文.
Now in the sum()
function the this
keyword had the same context as it does in the callSum()
and applySum()
functions.
call()
和apply()
之间的区别在于apply的第二个参数是要传递的参数数组或arguments
对象.
The difference between call()
and apply()
is that apply's second parameter is either an array of parameters to pass or an arguments
object.
这篇关于我可以通过"this"吗?作为javascript中另一个函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!