简体   繁体   中英

How to get all the properties assigned to the function object in javascript?

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?

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
}

最直接的方法可能是这样的:

Object.getOwnPropertyNames(func);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM