繁体   English   中英

我可以将“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)提醒变量时,显示相同的值但动画没有发生。 这适用于许多其他方式,但我试图传递单击以用于数学计算的列表项的索引值。

..或者我可以将值转换为第一个函数中的另一个变量,我可以传递给第二个函数吗?

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)); 

jsfiddle 示例链接

现在,在sum()函数中, this关键字与在callSum()applySum()函数中具有相同的上下文。

call()apply()之间的区别在于 apply 的第二个参数是要传递的arguments数组或arguments对象。

你可以通过this来像这样的另一个功能:

moveToNextImage(this, stepClicked);

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

在您的代码中,这一行是什么意思:

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

它应该是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM