Reputation: 2584
I am new to javascript so please understand if the question is a bit naive. I have heard that functions are also objects in javascript . So that means functions can also have properties like objects. So I tried this :
var foo=function(){
var v1=1;
console.log(foo.v1);
};
foo();
The output of this is undefined
. I dont understand what is happening. So when I declare the variable v1
in the function foo
,according to the result v1
is not a property of the function-object foo
.If it is not the former then what is it a property of ? Could some one explain to me what is happening ?
Upvotes: 0
Views: 54
Reputation: 113886
Object properties and variables are not the same thing. Functions can have both local variables (this includes function arguments) and properties:
function foo () {
v1 = 1; // this is a local variable
return [
v1, // local var above
foo.v2 // object property
]
}
foo(); // returns [1,undefined]
foo.v2 = 2;
foo(); // returns [1,2]
So you see, functions are indeed objects. But variables inside the function have nothing to do about the fact that functions are objects.
Side note: the fact that functions are first-class objects and that functions can be defined anonymously (without a name) are two different features. In C for example, functions are also first-class objects - that is, you can assign them to function pointers. But in C you can't declare functions without a name.
function bar() {}
b = bar; // this demonstrates that functions are first-class objects
c = function(){}; // this demonstrates that functions can be anonymous
Upvotes: 0
Reputation: 1428
You're right in Javascript function is a object. You can have attribute in a function object, examples are link length etc.
according to the result v1 is not a property of the function-object foo.
v1 is just a variable defined in function foo, it is not a attribute.
To add a attribute you could use foo.v1 = "1"
to add attribute v1 to object foo.
If you use console.log(v1) instead of console.log(foo.v1). You'll see output 1. Here you're accessing a local variable inside a function.
You might think var foo is already a object why can't I access it inside the function? This because these two foo variables are in different scopes. You might want to learn more about function scope
Upvotes: 1