何时在JavaScript中使用self [英] When to use self in JavaScript

查看:147
本文介绍了何时在JavaScript中使用self的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到像 setTimeout()之类的调用工作:

I've noticed that calls like setTimeout() work either as :

self.keyword()

或仅仅依靠自己,例如关键字()

or just on their own e.g. keyword().

这两个电话有什么不同?

What is the different between the two calls?

推荐答案

self 可以引用窗口对象,但通常情况并非如此。你会在上面看到这个 setTimeout()

self can refer to the window object, but typically that's not the case here. You'll see this commonly above that setTimeout():

var self = this;

他们保留对当前对象的引用,所以稍后你打电话给 self.keyword()你在那个对象上调用那个方法,而不是任何其他方法。

They're keeping a reference to the current object, so later when you call self.keyword() you're calling that method on that object, not any other.

假设您在页面中有想要每2秒轮换一次的图像...您希望这3个计时器中的每一个都参考他们的拥有方法。如果他们直接使用这个,它会(大部分时间)引用窗口而不是当前对象,而传递另一个变量来保持当前的引用。

Say you have for example images in the page you wanted to rotate every 2 seconds...you'd want each of those 3 timers to refer to their own methods. If they use this directly, it would (most of the time) refer to window and not the current object, whereas passing another variable in maintains the current reference.

这篇关于何时在JavaScript中使用self的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆