Reputation: 21
I'm fairly new to javascript objects and I could use some clarification on calling variables. I'm trying to call the test variable in the bar function. Is this possible? If so how would I do it correctly?
var foo = {
bar: function()
{
var test = 'Hello World';
},
speak: function()
{
// Log the Variable from above ^^
console.log(foo.bar.test);
}
};
Thanks
Upvotes: 0
Views: 62
Reputation: 4753
When you declare a local variable inside the function, you add it to the VariableEnvironment
of the functions (which essentially has no difference from the outer LexicalEnvironment
, but the ECMA distinguishes them). The function has a reference to the LexicalEnvironment
of the scope in which it was declared (in our case, the global object or window). When you try to reference the variable from inside the function, the engine first searches for it the the native VariableEnvironment
of the function, and then, if not found, in the outer LexicalEnvironment
. In your case, you try to reference a variable from outside of the function, so the engine searches for it in the scope of global object at the very start.
So, to accomplish your task, you should either declare the variable in the outer scrope, and then assign it inside the function, or you should add a new property to the object and then reference it:
var foo = {
test: 'Hello world',
speak: function()
{
console.log(this.test);
}
};
Upvotes: 1
Reputation: 2066
In order to access the variable test in that manner, you need to define it as a property of the object like so:
var foo = {
test: 'Hello World, before calling bar()',
bar: function()
{
this.test = 'Hello World';
},
speak: function()
{
// Log the Variable from above ^^
console.log(this.test);
}
};
console.log(foo.test);
I also changed the functions to access the object foo using the keyword this. It will usually work but keeping track of your scope in javascript can be tricky sometimes, so just try to be aware of that.
Upvotes: 0
Reputation: 23208
You can access test by return it on call of bar method.
var foo = {
bar: function()
{
var test = 'Hello World';
return test;
},
speak: function()
{
// Log the Variable from above ^^
console.log(foo.bar());
}
};
Upvotes: 0
Reputation: 887547
No; local variables are not visible outside their declaring functions.
Instead, you need to add a property to the object:
foo.test = ...;
You could also set foo.bar.test
; that would add a property to the function object.
Upvotes: 2