我在WebKit HTML 5 SQL Storage Notes Demo的源代码中看到了以下内容:
function Note() {
var self = this;
var note = document.createElement('div');
note.className = 'note';
note.addEventListener('mousedown', function(e) { return self.onMouseDown(e) }, false);
note.addEventListener('click', function() { return self.onNoteClick() }, false);
this.note = note;
// ...
}
作者在某些地方使用self(函数体),在其他地方使用this(在方法的参数列表中定义的函数体)。这是怎么呢现在我已经注意到它一次了,我将开始到处看到它吗?
还应该注意的是,如果您不喜欢var self = this习惯用法,还有另一种代理模式用于在回调中维护对原始this的引用。
可以使用function在给定的上下文中调用函数。应用或作用调用时,您可以编写一个包装器,该包装器返回一个函数,该函数使用apply或Call使用给定上下文调用您的函数。有关此模式的实现,请参阅jQuery的代理函数。下面是一个使用它的例子:
var包装func = $.proxy代理(这个。myFunc, this);
然后可以调用wrappedFunc,并将此版本作为上下文。
It's a JavaScript quirk. When a function is a property of an object, more aptly called a method, this refers to the object. In the example of an event handler, the containing object is the element that triggered the event. When a standard function is invoked, this will refer to the global object. When you have nested functions as in your example, this does not relate to the context of the outer function at all. Inner functions do share scope with the containing function, so developers will use variations of var that = this in order to preserve the this they need in the inner function.