且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

何时在JavaScript中使用self

更新时间:2023-10-21 23:17:52

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.