Can I pass "this" as a parameter to another function in javascript
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));
jsfiddle example link
Now in the sum()
function the this
keyword had the same context as it does in the callSum()
and applySum()
functions.
The difference between call()
and apply()
is that apply's second parameter is either an array of parameters to pass or an arguments
object.
You can pass this
to another function like so:
moveToNextImage(this, stepClicked);
function moveToNextImage(obj, stepClicked) {
var index = $(obj).index;
}
In your code, what does this line mean:
$($(this)).addClass('cs_current');
It should be:
$(this).addClass('cs_current');