Can I pass "this" as a parameter to another function in javascript

I have it:

$('#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 warning shows the correct index for clicking li, and when I warn the variable in the last function that I call, moveToNextImage(stepClicked) , the same value shows, but the animation does not happen. This works in many other ways, but I'm trying to pass in the index value of the list item that needs to be used to calculate math.

.. or can I convert the value to another variable in the first function, which I can pass to the second?

+4
source share
2 answers

The javascript functions call() and apply() are intended as for calling a function in 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)); 

jsfiddle link

Now in the sum() function, the this had the same context as in the callSum() and applySum() functions.

The difference between call() and apply() is that applying the second parameter is either an array of passed parameters or an arguments object.

+1
source

You can pass this to another function, for example

 moveToNextImage(this, stepClicked); function moveToNextImage(obj, stepClicked) { var index = $(obj).index; } 

In your code, what this line means means

 $($(this)).addClass('cs_current'); 

he should be like

 $(this).addClass('cs_current'); 
+3
source

Source: https://habr.com/ru/post/1402752/


All Articles