1

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?

vikrant
  • 2,169
  • 1
  • 21
  • 27
  • that's not my question actually, console.dir is still printing function, i want the property list of the function object. `console.log({ ...func })` works in this case – vikrant Jul 15 '18 at 18:17

3 Answers3

3

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
}
UtkarshPramodGupta
  • 7,486
  • 7
  • 30
  • 54
1

The most straightforward way might be this:

Object.getOwnPropertyNames(func);
Alex Feinstein
  • 393
  • 3
  • 12
0

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);
sachav
  • 1,316
  • 8
  • 11