对象字面量问题 - return 闭包

Problem with object literal - return closure

我有一个包含不同方法的模块 其中一个方法在 setTimeout 上调用其他方法,我需要将一些值传递给第二个方法,该方法称为

我首先这样做

transitSlide: function() {
        var left = parseInt(this.$ul.first().css('left')),
        newLeft = parseInt(left) + 100 ,
        index = (newLeft / 100),
        bool = (newLeft <= (this.slideShow.length - 1) * 100); // this is always TRUE

        this.$a.removeClass();
        this.$ul.addClass('fade');

        setTimeout(this.changeSlide.bind(this), 400);


        return bool; // I need to pass newLeft variable too !!!
}

changeSlide() {
    if (this.transitSlide) {
        alert('true') // this works!
    } else {
        alert('false')
    }
}

但我需要传递更多的值然后我这样做了

transitSlide: function() {
        var left = parseInt(this.$ul.first().css('left')),
        newLeft = parseInt(left) + 100 ,
        index = (newLeft / 100);

        this.$a.removeClass();
        this.$ul.addClass('fade');

        setTimeout(this.changeSlide.bind(this), 400);

        return  {
        direction: (newLeft <= (this.slideShow.length - 1) * 100) ? true : false, // this is always TRUE
        // direction: true // also doesnt work !!!
        newLeft: newLeft
        }
}

changeSlide() {
    if (this.transitSlide.direction) {
        alert('true')
    } else {
        alert('false') // this doesnt work!
    }
}

但即使我只输入真值,第二种方法也不 return 正确 然后我发现我应该 () 调用它 然后我写了

transitSlide: function() {
        var left = parseInt(this.$ul.first().css('left')),
        newLeft = parseInt(left) + 100 ,
        index = (newLeft / 100);

        this.$a.removeClass();
        this.$ul.addClass('fade');

        setTimeout(this.changeSlide.bind(this), 400);

        return  {
        direction: (newLeft <= (this.slideShow.length - 1) * 100) ? true : false, // this is always TRUE
        newLeft: newLeft
        }
}

changeSlide() {
        if (this.transitSlide().direction) {
                alert('true') // this works! but setTimeout call it over and over !!!
        } else {
                alert('false')
        }
}

但是 setTimeout 使它 运行 一遍又一遍(无限循环)

遇到这种情况我该怎么办? 如何在不调用第二个函数的情况下传递这些值并访问它们

函数 return 值未存储在任何地方;他们只是 returned 给来电者。

当您使用 setTimeout():

调用它时,听起来您实际上想将该状态作为参数传递给第二个函数
setTimeout(() => otherFunction(parameters))

使用apply()方法传递参数和this关键字

transitSlide: function() {
    var left = parseInt(this.$ul.first().css('left')),
        newLeft = parseInt(left) + 100 ,
        index = (newLeft / 100),
        direction = (newLeft <= (this.slideShow.length - 1) * 100);


    this.$a.removeClass();
    this.$ul.addClass('fade');

    setTimeout(this.changeSlide.apply(this, [direction, newLeft]), 400);

},

changeSlide(direction, newLeft) {
    if (direction) {
        alert(true)
    } else {
        alert(false)
    }
},