-2

I want to make object in javascript(like class but it is not support for es5/6 on my browser).My goal is get this of function in callback of Jquery.

Code

var log = e => console.log(e);

$(function(){
    var oop = new _oop();
})

var _oop = function(){
  this.testVariable = 0;
  $.get(url,function(){
    log(this.testVariable);//undefined
  });
}

That Variable is point at selector by jquery,I could not thought another ideas,just use "var" instead of "this" could deal this.

----supported 2-13----

To satisfy Browser in low level,I can't use arrow function in this case. The above one arrow in my code is for dev-mode.

----supported 2-13---- Fixed it.thx for all. Code

var log = e => console.log(e);

$(function(){
    var oop = new _oop();
})

var _oop = function(){
  this.testVariable = 0;
  var cb = function(){log(this.testVariable);}
  $.get(url,cb.bind(this));
}
cweiske
  • 30,033
  • 14
  • 133
  • 194
Rach Chen
  • 1,322
  • 2
  • 10
  • 26
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – JJJ Feb 13 '17 at 08:05

1 Answers1

0

The reason you are getting undefined is because you are trying to use this inside an anonymous function.

Try swapping it to use a fat arrow function to maintain the scope of this.

var log = e => console.log(e);

$(function() {
  var oop = new _oop();
})

var _oop = function() {
  this.testVariable = 0;
  $.get(url, () => {
    log(this.testVariable);
  });
}
Zze
  • 18,229
  • 13
  • 85
  • 118