我在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"
    });
};

箭头函数没有自己的这一点,只是简单地假定封闭作用域。

其他回答

我认为变量名“self”不应该再这样使用了,因为现代浏览器提供了一个全局变量self,指向普通窗口或WebWorker的全局对象。

为了避免混淆和潜在的冲突,可以写成var this = this或var that = this。

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.

是的,到处都能看到。that = this;

看到self是如何在事件调用的函数中使用的吗?它们将有自己的上下文,因此self用于保存进入Note()的this。

尽管self只能在Note()函数完成执行之后执行,但函数仍然可以使用self的原因是,由于闭包,内部函数获得了外部函数的上下文。

function Person(firstname, lastname) {
  this.firstname = firstname;

  this.lastname = lastname;
  this.getfullname = function () {
    return `${this.firstname}   ${this.lastname}`;
  };

  let that = this;
  this.sayHi = function() {
    console.log(`i am this , ${this.firstname}`);
    console.log(`i am that , ${that.firstname}`);
  };
}

let thisss = new Person('thatbetty', 'thatzhao');

let thatt = {firstname: 'thisbetty', lastname: 'thiszhao'};

this.sayHi.call(thatt);

该变量由该方法中定义的内联函数捕获。函数中的This将引用另一个对象。通过这种方式,您可以使该函数在外部作用域中保存对This的引用。