使用setTimeout从类中的单击处理程序集调用javascript类函数

时间:2014-09-23 11:40:02

标签: javascript jquery html class

我想定义一个javascript类,在我的html页面中实例化它的一个实例,然后让类设置一个click处理程序,然后使用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进行两次调用?

1 个答案:

答案 0 :(得分:1)

你试过了吗??

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');
    }
});