In C++, the language I\’m most comfortable with, usually one declares an object like this:
class foo
{
public:
int bar;
int getBar() { return bar; }
}
Calling getBar() works fine (ignoring the fact that bar might be uninitialized). The variable bar within getBar() is in the scope of class foo, so I don\’t need to say this->bar unless I really need to make it clear that I\’m referring to the class\’ bar instead of, say, a parameter.
Now, I\’m trying to get started with OOP in Javascript. So, I look up how to define classes and try the same sort of thing:
function foo()
{
this.bar = 0;
this.getBar = function() { return bar; }
}
And it gives me bar is undefined. Changing the bar to this.bar fixes the issue, but doing that for every variable clutters up my code quite a bit. Is this necessary for every variable? Since I can\’t find any questions relating to this, it makes me feel like I\’m doing something fundamentally wrong.
EDIT: Right, so, from the comments what I\’m getting is that this.bar, a property of an object, references something different than bar, a local variable. Can someone say why exactly this is, in terms of scoping and objects, and if there\’s another way to define an object where this isn\’t necessary?





Rating:
The post scope – Javascript: Do I need to put this.var for every variable in an object? appeared first on Javascript ASK.
via Javascript ASK http://javascriptask.phpfogapp.com/scope-javascript-do-i-need-to-put-this-var-for-every-variable-in-an-object.html
No comments:
Post a Comment