Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

javascript - JavaScript惯用语的基础是什么:var self = this?(What underlies this JavaScript idiom: var self = this?)

I saw the following in the source for WebKit HTML 5 SQL Storage Notes Demo :(我在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;
  // ...
}

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?(既然我已经注意到它了,我是否会开始到处看到它?)   ask by Thomas L Holaday translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

See this article on alistapart.com .(请参阅alistapart.com上的这篇文章 。)

(Ed: The article has been updated since originally linked)((编辑:自最初链接以来,该文章已更新))

self is being used to maintain a reference to the original this even as the context is changing.(self被用于保持对原始参考this甚至作为上下文正在改变。)

It's a technique often used in event handlers (especially in closures).(这是事件处理程序中经常使用的一种技术(尤其是在闭包中)。)

Edit: Note that using self is now discouraged as window.self exists and has the potential to cause errors if you are not careful.(编辑:请注意,现在不建议使用self作为window.self存在,并且如果不小心的话有可能导致错误。)

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 (eg 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" }); 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...