0

I don't understand what's going on here. If I do this:

function foo() {
  return 'hey there';
}
foo.value = 'some random value';

console.log(foo.value) // 'some random value';
console.log(typeof foo) // 'function'
console.log(foo) // ƒ foot()...

I can access later foo.value without problem but if I do typeof foo it returns function.

Where is foo.value being stored. Is definitely not in the global object. Can a function store properties then?

oquiroz
  • 85
  • 5
  • 14

2 Answers2

0

Functions are objects, and they can have properties on them. Some properties already exist without you doing anything. For example, you can do the following:

function test() {}

console.log(test.name);

so when you do:

foo.value = 'some random value';

you're just adding an additional property on that object.

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • and why does typeof returns 'function' instead of 'object'? Does it looks at the constructor or something like that? – oquiroz Jan 01 '19 at 16:13
  • That's just how the typeof operator is specified to work: function objects return the string 'function', nulls and other objects return 'object'. I doubt its looking at the constructor, though i don't know the details of how it is implemented. – Nicholas Tower Jan 01 '19 at 16:16
  • @oquiroz If it's an object and not callable you get `object`, if it's an object and callable you get `function`. – Bergi Jan 01 '19 at 16:21
  • @oquiroz when speaking of types in OO, we tend to speak of the most specific type, knowing that there's a lineage of more abstract types related to it. So an Apple is a kind of Fruit, and you have an apple in your hand, its type is Apple (which is a kind of Fruit, which is a kind of Object) – danh Jan 01 '19 at 16:22
0

Can a function store properties then?

Yes. A function is an object of type function and as with all objects you can assign properties to it.

This behaviour can be used to model static properties and methods on functions/classes.

function Foo() {
    this.value = 'instance';
}

Foo.value = 'static';
console.log(Foo.value);
console.log(new Foo().value);
dee-see
  • 23,668
  • 5
  • 58
  • 91