I was recently introduced into learning JavaScript and I was literally confused when I went through the prototype
concepts. Everything I read and understood got confused.
Let be get straight through..
I have two questions related to functions and Objects.
Question 1:
Can functions in JS have (key, value) pair of property in it? If so, what might me the data type of the key? Because In an Object, the key
of the property
can be only of the types String
, Object
and in some special cases Symbol
.
Question 2:
How are the functions evaluated internally? Are they converted to objects?
function sample () {
// code goes here
}
and
let myFunc = new Function(,,);
Thanks
It seems your overall question is “what are functions”.
Yes, functions are objects*. That’s why they are first-class citizens. They are just like any other value. Just like other objects they can have properties (you might be familiar with f.call
, f.bind
, etc).
What distinguishes functions from other objects is that they have an internal [[Call]]
property (internal properties cannot be accessed from user code, they are used in the specification to define internal state/behavior of objects).
The [[Call]]
property contains some representation of the code in the body of the function. It’s this code that is executed when the function is called.
There are other internal properties needed for a function to work, but [[Call]]
is the most important one. It is used to determine whether an object is callable or not.
Prototypes are not primarily related to functions. Prototypes are a concept applying to objects in general. They are not very complicated either: a prototype is a just an object. What makes an object a prototype is that another object has a reference to it via its internal [[Prototype]]
property. Then we can say “this object is the prototype of the other object”.
Other languages work similarly. Python for example lets you make instances of classes callable by implementing the magic def __call__:
method.
*: There are seven data types in JavaScript:
The first six are so called “primitive” data types.