6

In JavaScript functions are first-class objects, that means you can treat them just like any object, in this case, you are only adding a property to the function object.

Ok, let's add some properties to a function.

  function a() {
    a.firstProp = "I'm 1st - property";
  }

  a.seccondProp = "I'm 2st - property";

  function b() {
    a();
  }

  b(); // initialize 1st property (firstProp)  for `function a`;

  console.log( Object.getOwnPropertyNames(b) );
  console.log( Object.getOwnPropertyNames(a) );

How can I see in Chrome DevTools a key-value pair that I added to the function in code example?

0

5 Answers 5

4
  Console.log( Object.keys(a) );
2

You could use Object.assign, which copies own enumerable properties, to an empty object and have a look.

Or use Object.entries.

function a() {
    a.firstProp = "I'm 1st - property";
}

a.seccondProp = "I'm 2st - property";

function b() {
    a();
}

b(); // initialize 1st prop;

console.log(Object.assign({}, a));
console.log(Object.entries(a));

2
  • 1
    Or just use Object.keys.
    – dfsq
    Mar 24, 2018 at 9:34
  • This is the only answer that noticed the key-value pair phrase in the question. Mar 26, 2018 at 20:26
1

You are adding enumerable properties firstProp and secondProp. To get such properties you would usually use Object.keys method:

function a() {
  a.firstProp = "I'm 1st - property";
}

a()

a.seccondProp = "I'm 2st - property";

console.log(Object.keys(a))

1

The other ways are shorter and superior but you might be also interested in the for in loop. For in loops over ALL the properties like this:

function foo (){}

foo.bar = 'test';
foo.baz = 123;

for(let i in foo) {

  console.log(i);

}


console.log('------------');

for(let i of foo) {

  console.log(i);

}

Also note that the for in loop loops over all the properties of an object. The for of loop only loops over the object if the object is iterable (e.g. array), that's why this will produce an array.

Hope you find this helpfull.

1
+50

You can use:

console.dir(a);
console.dir(b);

And you will have this response in the console: enter image description here

Hope this helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.