Why Does Function Variable Can Have Object Property And Number Variable Not?
Solution 1:
Why console.log(abc);
of the first snippet is showing only the function body, without the prop
property?
Because that's what console.log()
is defined to do:
"If it's a function, just display its body."
How can I get Function
object's properties?
You can use
Object.getOwnPropertyNames(abc)
for all properties' names,Object.keys(abc)
for the enumerable properties' names,Object.values(abc)
for the enumerable properties' values,Object.entries(abc)
for both enumerable properties' names and values.
like any other Object
s.
Solution 2:
In JavaScript, functions are first-class objects, so are treated as such. Since in your first snippet you have declared the variable abc to be of type 'function', it can have properties, just like any other js object. In the second snippet you have declared it to be of type number, which does not allow you to declare properties.
See this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions
Solution 3:
According to MDN:
Data types:
The latest ECMAScript standard defines seven data types:
- Six data types that are primitives:
- Boolean
- Null
- Undefined
- Number
- String
- Symbol (new in ECMAScript 6)
- and Object
The primitive values do not inherit from Object
so you can't assign properties to them.
The primitive values are copied instead of passed around using a reference to them.
You can assign properties to numbers, if the numbers are instances of Number
:
var abc = newNumber(55); // abc inherits from Object via the Number class
abc.prop = 1; // so this is validconsole.log(abc);
console.log(abc.prop);
Note: The console log of abc
is wrong because SO's console.log
logs abc
as an object where it should log it as a number. Use the browser console instead. (abc
indeed is an object as it inherits from Object
via the class Number
, but it should be logged as a number since it is an instance of Number
).
Post a Comment for "Why Does Function Variable Can Have Object Property And Number Variable Not?"