1

我在 JavaScript 中创建了一个秒表类,当用户单击“开始秒表”按钮时,秒表应该启动。

我的问题是,当用户单击“开始秒表”按钮时,“this”引用的是按钮而不是 Stopwatch 对象。

有什么建议么?

这是一个示例: https ://c9.io/rjfreund/stopwatch/workspace/stopwatch.html

4

3 回答 3

3

由于您使用的是 jQuery:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

...使用.bind().on()绑定处理程序,并在event-data中设置对象。

$('.yourElement').on("click", {obj: yourObject}, function(event) {
    alert(event.data.obj);
});
于 2012-11-06T19:33:19.887 回答
0

This is the best I can do without code:

<a id="start_stopwatch" onclick="yourStopwatchClass.start.call(yourStopwatchClass)">Start stopwatch!</a>

call refers the this variable to whatever you pass in, in this case your Stopwatch class.

于 2012-11-06T19:33:54.357 回答
0

函数的值this由函数的调用方式设置。对于侦听器,如果分配如下:

element.onclick = instance.method;

然后它将被处理程序或多或少地作为元素的方法调用,并将其设置this为元素。使用其他方法(和各种库方案)附加侦听器addEventListener会做同样的事情。

您可以使用callor apply,但您也可以包装该函数并调用它来设置this您想要的对象:

element.onclick = funciotn() {insance.method()};

您还可以使用bindES5 提供的各种库和shims

于 2012-11-06T21:08:33.253 回答