Reputation: 4063
I was trying to understand the scope of variables in javascript objects. But the behavior that I am getting seems to be a little off the road. To put it simply, if I have an object that defines a function as a variable, then the function variable is not able to access other variables of the object in which it is defines. The code below will make things clear.
<html>
<head>
<script type="text/javascript">
var someObject = {
someVariable : 5,
getVariable: function() {
return someVariable;
}
};
window.onload = function () {
alert(someObject.getVariable());
};
</script>
</head>
<body>
Hello There
</body>
</html>
The above code gives "ReferenceError: someVariable is not defined" for the someVariable in function getVariable(). Would anyone like to comment on this behavior?
Upvotes: 1
Views: 126
Reputation: 26696
Absolutely.
The "variable" you're talking about isn't a "variable", it's a property
of an object (the object happening to be a variable).
As such, you have two options.
Assuming that your object is made like this:
var obj = {
property : 42,
everything : function () { /* ... */ }
};
The two options for inside of your function body, to return the value 42 are:
obj.property;
OR
this.property;
When you call:
obj.everything();
The JS interpreter will see obj
as being equal to this
inside of the function.
Or you reference obj
itself, directly, and access property
using either .property
dot-notation, or ["property"]
bracket-notation.
Upvotes: 3
Reputation: 262474
That is not a variable, that is a property/field of an object.
Try this.someVariable
.
Here this
is a (rather special) variable that points to the object, and the dot (or square bracket) syntax can be used to access fields of that object.
You can also do someObject.someVariable
in places where someObject
(another variable pointing at the object) is in scope.
Upvotes: 1
Reputation: 2599
Try this.someVariable
:
var someObject = {
someVariable: 5,
getVariable: function () {
return this.someVariable;
}
};
window.onload = function () {
alert(someObject.getVariable());
};
Upvotes: 0