Reputation:
If functions are objects in javascript, why can't I access the function scope defined variables?
I understand that in the code:
// variable test assigned an anonymous function
var test = function(){
var x = 5;
};
console.log(test.x); // undefined
// Even when the function is explicitly named:
function test(){
var x = 5;
}
console.log(test.x); // undefined
I don't need to get this working or anything; I just need to understand why functions are like this.
Thanks.
Upvotes: 1
Views: 1134
Reputation: 1108
var someName = function(){var x ...} /// only has local scope.
What is the scope of variables in JavaScript?
Will describe it better than I can. Good job on being curious and motivated.
Upvotes: 0
Reputation: 231
I believe it is because those variables only exist within the scope of the function you have defined. Outside the scope of that function they do not exist.
They are the equivalent of private members in a class of an object oriented language.
Alternatively you could have
function test() {
this.x = 5;
}
var testInstance = new test();
console.log(test.x);
Upvotes: 0
Reputation: 6120
This would be one way to accomplish what you are trying:
function test() {
this.x = 5;
}
var foo = new test();
console.log(foo.x);
Using var x
rather than this.x
just declares a local variable
Upvotes: 2
Reputation: 1103
You have created Local variables. Local variable can only be accessed within the function.
Try to understand about Local & Global JavaScript Variables
Local JavaScript Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables have local scope: They can only be accessed within the function.
function myFunction() {
var name = "roy";
// code here can use name
}
Global JavaScript Variables
A variable declared outside a function, becomes GLOBAL.
A global variable has global scope: All scripts and functions on a web page can access it.
var name = "roy";
// code here can use name
function myFunction() {
// code here can use name
}
Upvotes: 0
Reputation: 40
The variable is visible only in the function and it is possible to access it only within the function, you can use global variable and then edot it insode the function.
Upvotes: 0
Reputation: 6147
Functions are objects, but that doesn't mean that any variable declared inside the function becomes a property of that function object. In fact, that would be terrible because you wouldn't be able to run a function more than once (since the second time, the variables would start with different values).
You can assign a property to a function object like this:
var test = function () {};
test.x = 5
Upvotes: 0