这个 JavaScript 习语的基础是什么:var self = this? [英] What underlies this JavaScript idiom: var self = this?

查看:23
本文介绍了这个 JavaScript 习语的基础是什么:var self = this?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 WebKit HTML 5 SQL Storage Notes Demo 的源代码中看到了以下内容:>

I saw the following in the source for 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.这是怎么回事?现在我已经注意到它一次,我会开始到处看到它吗?

The author uses self in some places (the function body) and this in other places (the bodies of functions defined in the argument list of methods). What's going on? Now that I've noticed it once, will I start seeing it everywhere?

推荐答案

参见 alistapart.com 上的这篇文章.(Ed:文章自最初链接后已更新)

See this article on alistapart.com. (Ed: The article has been updated since originally linked)

self 被用来维护对原始 this 的引用,即使上下文发生变化.这是一种经常用于事件处理程序(尤其是在闭包中)的技术.

self is being used to maintain a reference to the original this even as the context is changing. It's a technique often used in event handlers (especially in closures).

请注意,现在不鼓励使用 self 作为 window.self 存在,如果不小心可能会导致错误.

Note that using self is now discouraged as window.self exists and has the potential to cause errors if you are not careful.

你怎么称呼这个变量并不重要.var that = this; 很好,但这个名字并没有什么神奇之处.

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 (e.g. 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"
});

这篇关于这个 JavaScript 习语的基础是什么:var self = this?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆