我有一个使用不同方法的模块 其中一种方法在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!
}
}
,但是即使我只输入true值,它也不会对第二种方法返回true 然后我发现我应该()调用它 然后我写了
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使其反复运行(不定式循环)
在这种情况下我该怎么办? 如何在不调用它们的情况下传递这些值并在第二个函数中访问它们
答案 0 :(得分:0)
函数返回值不存储在任何地方;他们只是返回给呼叫者。
听起来好像您实际上想在使用setTimeout()
进行调用时将该状态作为参数传递给第二个函数:
setTimeout(() => otherFunction(parameters))
答案 1 :(得分:0)
使用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)
}
},