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.
Yes, this is accepted practice. See this article on scope or this question.
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.
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.
$ 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).
Yes, this is accepted practice. See this article on scope or this question.
Reading up on closure may also be helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With