Javascript OOP 文字访问方法内的变量

标签 javascript oop

我在 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/

相关文章:

javascript - 这个循环是什么?

java - 构建器模式与配置对象

java - 我应该如何在Java中实现接口(interface)? [代码正确性]

c++ - C++中,为什么指针转换时地址变了?

java - 在两个类之间共享代码(使用抽象操作)

javascript - 原型(prototype)继承 - 为什么这行不通?

javascript - Jquery DatePicker 设置为不自动打开

javascript - 使用 html 代码和 javascript 代码作为 flutter web 中的小部件

javascript - 在输入组中引导 5 个 float 标签

c# - 向现有类添加新功能 (C#)