我在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)
它有效,但这是最好的方法吗?这对我来说很奇怪.
我一直在努力使用.bind()方法使用这些"this"并使用变量"self = this".在获得两个不同的结果时,我错过了一个概念.案例如下:
// Defining a callback class to use after retrieving data
var Callback = (function(){
// UPDATED!! Local vbles
var template_to_use, html_element, self;
function Callback(){
self = this,
template_to_use = null,
html_element = null;
}
var p = Callback.prototype;
p.set_template = function(template_funct){
self.template_to_use = template_funct;
};
p.set_html_element = function(html_element){
self.html_element = html_element;
};
p.use_callback = function(data){
$(self.html_element).append(self.template_to_use(data));
};
return Callback;
})();
Run Code Online (Sandbox Code Playgroud)
该功能的用法如下:
// Setup callback 1 to call after getting the data
var callback_1 = new Callback();
callback_1.set_template(use_templ_1); …Run Code Online (Sandbox Code Playgroud) 我很难获得承诺this在原型中使用正确的范围.
这是我的代码:
'use strict';
angular.module('testApp').factory('UrlSearchApi',
function($resource, URL_SEARCH_API, PAGE_SIZE, $q){
var resource = $resource(URL_SEARCH_API);
resource.Scroll = function () {
return this.reset();
};
resource.Scroll.prototype.reset = function () {
this.visibleItems = [];
this.allItems = [];
this.busy = null;
return this;
};
resource.Scroll.prototype.fetch = function(query){
var params = {};
if(query) { params.q = query; }
return resource.query(params).$promise;
};
resource.Scroll.prototype.loadAllItems = function (results) {
var d = $q.defer();
angular.forEach(results, function (result, i) {
this.allItems.push(result);
if(i === results.length - 1 ) { d.resolve(); } …Run Code Online (Sandbox Code Playgroud)