Reputation: 2277
In javascript I can create an object with the same name as a function, or i can assign a new property to the function object, like:
function func(){
console.log("inside func");
}
func.a = "new property";
console.log(func.a);
func();
console.log(func);
How do i see what are the properties assigned(and possibly their values) to the function object?
Upvotes: 1
Views: 923
Reputation: 391
The most straightforward way might be this:
Object.getOwnPropertyNames(func);
Upvotes: 1
Reputation: 8152
Functions are special type of Objects in JavaScript.
Unlike other programming languages, functions are special type of Objects in JavaScript. They have their own methods (viz. bind, call, apply and a hell lot more) like other objects do. Therefore, when you assign a prop a
to your func
, you are not creating a new func
object. Instead, it's the same func
object (function object) and you are just creating a new prop func.a
on it. Read this for more info. Also, you can do something like the following to print all the props you have assigned to a function object (or any object in JS):
for (var prop in func) {
console.log(prop); // This will print 'a' in your case
}
Upvotes: 3
Reputation: 1316
The function is implicitely cast to string when console.log()
is called, and by default toString()
only returns the code of your function (see the documentation here).
function func(){
console.log("inside func");
}
func.toString = function() {
return "a = " + this.a;
}
func.a = "new attribute";
console.log(func.a);
func();
console.log(func);
Upvotes: 0