我在WebKit HTML 5 SQL存储笔记演示的源代码中看到以下内容:
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;
// ...
}
Run Code Online (Sandbox Code Playgroud)
笔者采用自我在一些地方(函数体)及本在其他地方(的函数方法的参数列表中定义的机构).这是怎么回事?现在我已经注意到了它,我会在各处开始看到它吗?
使用实例方法作为事件处理程序的回调改变的范围this从"我的实例"到"无论只是调用的回调".所以我的代码看起来像这样
function MyObject() {
this.doSomething = function() {
...
}
var self = this
$('#foobar').bind('click', function(){
self.doSomethng()
// this.doSomething() would not work here
})
}
Run Code Online (Sandbox Code Playgroud)
它有效,但这是最好的方法吗?这对我来说很奇怪.