使用变量self与此之间的区别 [英] Difference between using variable self vs this
问题描述
我一直在努力使用.bind()方法使用这些this并使用变量self = this。在获得两个不同的结果时,我错过了一个概念。案例如下:
I have been struggling with the use of these "this" with the .bind() method and the use of the variable "self = this". In getting two different results with those, so I'm missing one concept. The case is like follow:
// 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;
})();
此功能的用法如下:
// Setup callback 1 to call after getting the data
var callback_1 = new Callback();
callback_1.set_template(use_templ_1);
callback_1.set_html_element("#list");
// Get list data
api_list.get_data(callback_1.use_callback);
// Setup callback 2 to call after getting more data
var callback_2 = new Callback();
callback_2.set_template(use_templ_2);
callback_2.set_html_element("#object");
// Get object data
api_object.get_data(callback_2.use_callback);
执行两个ajax调用,一旦get_data()函数完成,它们将调用回调函数我传给了他们。我得到的问题是,在执行这些函数后,回调总是提到带有相应模板use_templ_2的html_element =#object。
Two ajax calls are executed and once the get_data() function is done, they will call the callback functions that I passed to them. The issue I'm getting is that after executing those functions, the callback is always mentioning the html_element = "#object" with the corresponding template "use_templ_2".
如果我使用this和.bind函数而不是selfvble,结果是预期的结果。
If I use "this" and .bind function instead of the "self" vble, the results are the expected ones.
// Get object data
api_object.get_data(callback_2.use_callback.bind(callback_2));
我缺少什么?这可能是一个错误的概念,因为即使我不是js的新手,我也是对语言本身的新理解。
What am I missing? It might be an error concept since even if I'm not new to js, I'm new understanding the language itself.
推荐答案
小心, self
将始终引用最后一个instanciated对象:
Be careful, self
will always refer to the last instanciated object :
var c1 = new Callback();
var c2 = new Callback(); // overrides previous self
然后以下行实际设置 c2.html_element
:
c1.set_html_element(html_element);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
那就是说,替换这个
对你来说完全没用。
That said, replacing this
is completely useless in your case.
这篇关于使用变量self与此之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!