我想定义一个 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/