[英]Scope of global variables in a Javascript class
我有一个自定义Javascript对象,如下所示:
var CustomClass = function(settings) {
this.var_1 = false;
this.var_2 = null;
this.var_3 = 0;
}
CustomClass.prototype.method_1 = function(){
var reader = new FileReader();
reader.onload = (function(cropWidget) {
this.var_1 = true;
});
}
CustomClass.prototype.method_2 = function(){
console.log(this.var_1); // logs 'false' onto the console
if(this.var_1)
{ // proceed further and do something
}
}
CustomObject实例化于:
$(document).ready(function{;
var customObj = new CustomClass({/*json values*/});
});
然后,另一个DOM事件将调用method_1,例如:
$('#element1').click(function(){
customObj.method_1(); // this is where var_1 is being set to true
});
当由另一个元素在DOM 中调用method_2()时,会发生问题 ,如下所示:
$('#element2').click(function(){
customObj.method_2();
});
它会检查var_1的值,您记得当customObj调用method_1时已将其设置为true
this.var_1为false,而不是应为true。 这是否意味着仅针对method_1()的范围将var_1的范围设置为true,并且仍保留其旧值? IMO Javascript通过引用传递,因此变量值应在其原始位置设置为true。
有人可以解释我要去哪里哪里以及如何设置var_1的值,以便它还能在method_2中保留它的新值吗?
this.var_1为false,而不是应为true。
这可能是因为您没有引用同一对象。 您的事件处理程序function(){ var customObj = new CustomClass(…); }
function(){ var customObj = new CustomClass(…); }
创建一个实例,并将其分配到一个局部变量 。 函数运行后将被垃圾回收。
IMO javascript是通过引用传递的,因此变量值应在其原始位置设置为true。
不,JavaScript始终是按值传递的。 但是,当您传递对象时,实际上是在传递引用该对象的值,因此会有很多变量引用同一“共享”对象。
问题在于您将var_1
设置为true的范围不是您想要的范围:
CustomClass.prototype.method_1 = function(){
var reader = new FileReader();
reader.onload = function(cropWidget) {
this.var_1 = true;
};
}
你设置var_
到true
的回调,和值this
回调是不一样的method_1
。
您可以使用self = this
习语来解决此问题:
CustomClass.prototype.method_1 = function(){
// "this" here refers to the CustomClass instance,
// so let's store it in "self" so we can use it in the callback
var self = this;
var reader = new FileReader();
reader.onload = function(cropWidget) {
// "this" here will not be the CustomClass instance,
// so we refer to the "self" variable from above.
self.var_1 = true;
};
}
那应该可以解决您的问题,尽管仍然存在潜在的计时问题:如果在FileReader
触发其onload
事件之前调用method_2
,则var_1
尚未设置为true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.