Assigning 'this' to a variable in Javascript

Viewed 9378

I'm taking an object oriented approach with Javascript, for two reasons. One, because it helps me learn, and two, just in case my code is to be distributed.

I already have assigning functions to variables and using this for public variables. I'm running into problems using this, however. When I'm in a "private" function, this refers to a different scope, and I can't access the variables under this. I'll illustrate my point.

var ClassObject = function() {
  this.var1 = 'Hello';

  var var2 = 786;

  this.func1 = function() {
    alert(this.var1); // Alerts Hello
    alert(var2); // Alerts 786
  }

  var func2 = function() {
    alert(this.var1); // Alerts undefined
    alert(var2); // Alerts 786
  }
}

The only way I've found to give func2 access to this.var1 was to make another variable assigned to this: var c = this. Is this the best way to go about this task, or even widely acceptable? Can anybody offer a better solution?

Thank you all.

3 Answers
Related