javascript - 从类中设置的点击处理程序中使用 setTimeout 调用 javascript 类函数

标签 javascript jquery html class

我想定义一个 javascript 类,在我的 html 页面中实例化它的实例,并让该类设置一个点击处理程序,然后使用 setTimeout(...) 调用该类的成员函数。

目前这对我来说不起作用,因为我很难理解确定我的类和/或创建的对象的调用和使用范围的正确方法。我希望有人能够帮助我解决下面的示例。

下面的代码有一些对 $(...) 的引用,它是 jquery,只是为了向可能读到此代码但不认识它的人澄清。

我在我的 JavaScript 代码中使用以下内容作为类的基础:

// Taken from http://www.htmlgoodies.com/html5/tutorials/create-an-object-oriented-javascript-class-constructor.html
// Base class from which we can derive our own classes with ease
var Class = function (methods) {
    var klass = function () {
        this.initialize.apply(this, arguments);
    };

    for (var property in methods) {
        klass.prototype[property] = methods[property];
    }

    if (!klass.prototype.initialize) klass.prototype.initialize = function () { };

    return klass;
};

然后我也在 JavaScript 中用我的类扩展了这一点:

var myNamespace = myNamespace || {};

myNamespace.myClass = Class({
    somevalue: 100,

    initialize: function(somevalue) {
        this.somevalue = somevalue;

        $("#searchclear").click(function () {
            setTimeout(myFunction,1000); // THIS DOES NOT WORK as the context is now the searchclear html element
            myFunction(); // For completeness, this would not work either for the same reason
        });
    }),

    myFunction: function() {
        alert('we are ok');
    }
});

我的 HTML 看起来像这样:

<body>
    ...
    <script>
        $(document).ready(function () {
            var myInstance = new myNamespace.myClass(123);
        });
    </script>
    <span id='searchclear'>CLICK ME</span>
    ...
</body>

问题是,如何在单击“searchclear”HTML 对象时调用的单击处理程序中对 myFunction 进行两次调用?

最佳答案

你尝试过吗:?

myNamespace.myClass = Class({
    somevalue: 100,

    var self = this;

    initialize: function(somevalue) {
        this.somevalue = somevalue;

        $("#searchclear").click(function () {
            setTimeout(self.myFunction,1000); // THIS DOES NOT WORK as the context is now the searchclear html element
            self.myFunction(); // For completeness, this would not work either for the same reason
        });
    }),

    self.myFunction: function() {
        alert('we are ok');
    }
});

关于javascript - 从类中设置的点击处理程序中使用 setTimeout 调用 javascript 类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25994164/

相关文章:

jquery - Fancybox 打开 href onclick

html - 媒体查询在 IE9 iframe 中失败

javascript - 使用 ng-include 时如何使作用域函数工作?

javascript - 如何仅停止当前页面进程,而不停止整个 NodeJS 服务器

javascript - 如何使用 TypeScript 为无状态、功能性 React 组件指定(可选)默认 Prop ?

javascript - 更新 d3 中的图表

javascript - 发送额外的 JSON 数据以及发送序列化表单数据的现有 AJAX 帖子

javascript - IE 中 JavaScript 函数的故障排除

html - 带有自定义标签的 CSS 宽度

javascript - json 对象的完整路径