Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning 'this' to a variable in Javascript

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.

like image 991
Matt Mancuso Avatar asked Aug 08 '12 05:08

Matt Mancuso


People also ask

Can we assign this to variable JavaScript?

Yes, this is accepted practice. See this article on scope or this question.

How do you assign a value to a variable in JavaScript?

You can assign a value to a variable using the = operator when you declare it or after the declaration and before accessing it. In the above example, the msg variable is declared first and then assigned a string value in the next statement.

How do you assign a value to this?

The first time a variable is assigned a value, it is said to be initialised. The = symbol is known as the assignment operator. It is also possible to declare a variable and assign it a value in the same line, so instead of int i and then i = 9 you can write int i = 9 all in one go.

What does '$' mean in JavaScript?

$ is simply a valid JavaScript identifier. JavaScript allows upper and lower letters, numbers, and $ and _ . The $ was intended to be used for machine-generated variables (such as $0001 ). Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function).


1 Answers

Yes, this is accepted practice. See this article on scope or this question.

Reading up on closure may also be helpful.

like image 57
Scotty Avatar answered Sep 19 '22 15:09

Scotty