简体   繁体   English

如何在javascript中获取分配给函数对象的所有属性?

[英]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:在 javascript 中,我可以创建一个与函数同名的对象,或者我可以为函数对象分配一个新属性,例如:

 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.函数是 JavaScript 中特殊类型的对象

Unlike other programming languages, functions are special type of Objects in JavaScript.与其他编程语言不同,函数是 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.因此,当您将 prop a分配给func ,您并不是在创建新的func对象。 Instead, it's the same func object (function object) and you are just creating a new prop func.a on it.相反,它是相同的func对象(函数对象),您只是在其上创建了一个新的 prop func.a 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):此外,您可以执行以下操作来打印您分配给函数对象(或 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 ).调用console.log()时,该函数会隐式转换为字符串,默认情况下toString()仅返回函数的代码(请参阅此处的文档)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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