开发者

javascript classes - is "this.varname" required for each use?

开发者 https://www.devze.com 2023-01-14 01:22 出处:网络
I have a javascript class like this: function Foo() { this.x = 5; this.y = x + 10; } Does \'x\' not get scoped to the instance of the class when I don\'t use \'.this\'? If so, how do we use callbac

I have a javascript class like this:

function Foo() {
  this.x = 5;
  this.y = x + 10;
}

Does 'x' not get scoped to the instance of the class when I don't use '.this'? If so, how do we use callbacks then? I have something like:

function Foo() {
  this.x = 5开发者_StackOverflow;

  this.grok = function() {
    jQuery(blah).animate({
      ..,
      function(){
        x = 55;
      }
    });
  }
}

so jquery gives a chance for a callback, but how do I access the 'x' member variable of the parent class in that context then?

Thanks


In your specific case, you have to store a reference to this in another variable:

function Foo() {
  this.x = 5;

  this.grok = function() {
      var that = this;
      jQuery(blah).animate({
        ..,
        function(){
          that.x = 55;
        }
      });
  }
}

The anonymous function has access to all variables defined in grok. If you just use x, it would be a global variable.


What you can do is to use another variable as a pointer to the correct this then use a closure to capture that variable:

function Foo() {
  this.x = 5;
  var foo_this = this;

  this.grok = function() {
    jQuery(blah).animate({
      ..,
      function(){
        foo_this.x = 55;
      }
    });
  }
}

Some people like to use the variable name that whenever they point to this. I personally prefer to use self.

0

精彩评论

暂无评论...
验证码 换一张
取 消