Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript how to get this.variable in callback function

In the following customized class in javascript, in callback, why does this.obj have nothing but local variable obj has thing I want? Thanks.

function ClassTest(director) {
  this.obj = {"test1": "test1"};
}

function test1(input, callback) {
  callback("success");
}

ClassTest.prototype.test = function() {
  var obj = this.obj;
  test1("niuniu",function(e){
    console.log(this.obj);  // undefined
    console.log(obj);  // this one has stuff
    });
}

// run 
new ClassTest().test()
like image 519
Linghua Jin Avatar asked Dec 05 '22 12:12

Linghua Jin


2 Answers

Because the function inside test1 is creating a new scope with different this context. Typical solutions are to bind or to cache this:

Binding:

test1("niuniu",function(e){
  console.log(this.obj);
}.bind(this));

Caching:

var self = this;
test1("niuniu",function(e){
  console.log(self.obj);
});
like image 145
elclanrs Avatar answered Dec 29 '22 01:12

elclanrs


As for this line of code:

console.log(obj);  // this one has stuff

The reason it works has to do with how JavaScript closure works. The code defined in your anonymous function has access to all variables in its local scope as well as variables defined in encompassing scopes and therefore obj is available. See How do JavaScript closures work? for more on closure.

The keyword this however, is a reference to the current scope. Because you are accessing this.obj from within the anonymous function, this refers to the anonymous function itself - which has no obj property defined. In the enclosing function, which is extending the ClassTest prototype, this refers to the current ClassTest object, which does have a obj property defined.

like image 40
coagulateblue Avatar answered Dec 29 '22 01:12

coagulateblue