javascript 我可以将“this”作为参数传递给javascript中的另一个函数吗
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9812445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I pass "this" as a parameter to another function in javascript
提问by kelly johnson
I have this:
我有这个:
$('#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);
};
});
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.
警报显示点击的 li 的正确索引,当我在我调用的最后一个函数中提醒变量时moveToNextImage(stepClicked)
,显示相同的值但动画没有发生。这适用于许多其他方式,但我试图传递单击以用于数学计算的列表项的索引值。
..or can I convert the value to another variable in the first function that I can pass to the second?
..或者我可以将值转换为第一个函数中的另一个变量,我可以传递给第二个函数吗?
采纳答案by Duncan Gravill
The javascript functions call()
and apply()
are both for precisely for the purpose of calling a function within a context.
javascript 函数call()
和apply()
两者都是为了在上下文中调用函数。
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));
Now in the sum()
function the this
keyword had the same context as it does in the callSum()
and applySum()
functions.
现在,在sum()
函数中,this
关键字与在callSum()
和applySum()
函数中具有相同的上下文。
The difference between call()
and apply()
is that apply's second parameter is either an array of parameters to pass or an arguments
object.
call()
和之间的区别在于apply()
apply 的第二个参数要么是要传递的参数数组,要么是一个arguments
对象。
回答by irfanmcsd
You can pass this to another function like
您可以将其传递给另一个函数,例如
moveToNextImage(this, stepClicked);
function moveToNextImage(obj, stepClicked) {
var index = $(obj).index;
}
In your code what is this line mean
在您的代码中,这一行是什么意思
$($(this)).addClass('cs_current');
it should be like
它应该像
$(this).addClass('cs_current');