我在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;允许闭包中的代码引用回父作用域。
然而,现在是2018年,所有主要的web浏览器都广泛支持ES6。var self = this;成语不像以前那么重要了。
现在可以避免var self = this;通过使用箭头函数。
在使用var self = this的情况下:
function test() {
var self = this;
this.hello = "world";
document.getElementById("test_btn").addEventListener("click", function() {
console.log(self.hello); // logs "world"
});
};
我们现在可以使用一个没有var self = this的箭头函数:
function test() {
this.hello = "world";
document.getElementById("test_btn").addEventListener("click", () => {
console.log(this.hello); // logs "world"
});
};
箭头函数没有自己的这一点,只是简单地假定封闭作用域。