function myclass()
{
var pri_var;
this.pub_var;
this.pub_func = function(which_object)
{
pri_var = which_object;
this.pub_var = which_object + " pub";
}
this.pub_func1 = function()
{
console.log(this);
alert(this.pub_var);
alert(pri_var);
}
}
instance1 = new myclass();
instance2 = new myclass();
instance1.pub_func("first");
instance2.pub_func("second");
//instance1.pub_func1();
//instance2.pub_func1();
function callCallback(callback1, callback2){
callback1("first");
callback2("second");
}
callCallback(instance1.pub_func1, instance2.pub_func1);
private 变量被正确记录,但 public 是未定义的,因为它指向 window 而不是 myclass 实例。
在类内部定义的回调中访问公共变量的解决方案是什么?
可能的答案
function myclass()
{
var pri_var;
this.pub_var;
var that = this;
this.pub_func = function(which_object)
{
pri_var = which_object;
that.pub_var = which_object + " pub";
}
this.pub_func1 = function()
{
console.log(this);
alert(that.pub_var);
alert(pri_var);
}
}
instance1 = new myclass();
instance2 = new myclass();
instance1.pub_func("first");
instance2.pub_func("second");
//instance1.pub_func1();
//instance2.pub_func1();
function callCallback(callback1, callback2){
callback1("first");
callback2("second");
}
callCallback(instance1.pub_func1, instance2.pub_func1);