See this article on alistapart.com .(请参阅alistapart.com上的这篇文章 。)
(Ed: The article has been updated since originally linked)((编辑:自最初链接以来,该文章已更新))
self
is being used to maintain a reference to the original this
even as the context is changing.(self
被用于保持对原始参考this
甚至作为上下文正在改变。)
It's a technique often used in event handlers (especially in closures).(这是事件处理程序中经常使用的一种技术(尤其是在闭包中)。)
Edit: Note that using self
is now discouraged as window.self
exists and has the potential to cause errors if you are not careful.(编辑:请注意,现在不建议使用self
作为window.self
存在,并且如果不小心的话有可能导致错误。)
What you call the variable doesn't particularly matter.(您所说的变量并不重要。)
var that = this;
is fine, but there's nothing magic about the name.(很好,但是名称没有什么魔术。)
Functions declared inside a context (eg callbacks, closures) will have access to the variables/function declared in the same scope or above.(在上下文中声明的函数(例如,回调,闭包)将有权访问在相同范围或更高范围中声明的变量/函数。)
For example, a simple event callback:(例如,一个简单的事件回调:)
function MyConstructor(options) { let that = this; this.someprop = options.someprop || 'defaultprop'; document.addEventListener('click', (event) => { alert(that.someprop); }); } new MyConstructor({ someprop: "Hello World" });
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…