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

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

问题描述

我在 WebKit HTML 5 SQL存储说明演示的源中看到了以下内容:

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 在某些地方(函数体)和在其他地方(函数参数列表中定义的函数体)。这是怎么回事?

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上的文章

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).

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

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