我在 OOP 中访问方法内的变量时遇到问题。
这是我的代码:
var slideshow = {
elSet : $(".slideshow"),
next : function() {
},
swipe : function() {
var clear = this.autorun().loop;
onSwipe(function() {
clearInterval(clear); // not working
});
},
autorun : function() {
var self = this;
var loop = setInterval(function() {
self.next();
}, 5000);
},
initial : function() {
this.swipe();
this.autorun();
}
}
slideshow.initial();
我想从变量循环中清除Interval,
在浏览器控制台返回错误 TypeError: this.loop(...) is undefined
我的代码有什么问题吗?
最佳答案
只需将 setInterval 返回的间隔 ID 分配给您可以访问的变量,或者像 Barmar 的答案一样返回它。
var slideshow = {
elSet: $(".slideshow"),
next: function() {
},
swipe: function() {
var self = this;
onSwipe(function() {
//use the interval id to cancel
clearInterval(self.intervalRef);
});
},
// variable to store the interval id
intervalRef: null,
autorun: function() {
var self = this;
//assign the interval id generated by setInterval to a variable you can access
this.intervalRef = setInterval(function() {
self.next();
}, 5000);
},
initial: function() {
this.swipe();
this.autorun();
}
}
slideshow.initial();
关于Javascript OOP 文字访问方法内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34524831/