I found very mysterious thing when I am using variable.
Please see below snippet.
var abc = function(){};
abc.prop = 1;
console.log(abc);
console.log(abc.prop);
var abc = 3;
abc.prop = 1;
console.log(abc);
console.log(abc.prop);
I found very mysterious thing when I am using variable.
Please see below snippet.
var abc = function(){};
abc.prop = 1;
console.log(abc);
console.log(abc.prop);
var abc = 3;
abc.prop = 1;
console.log(abc);
console.log(abc.prop);
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."
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 Objects.
console.dir instead of console.log to list properties of an object (function, ...). Try it!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
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 = new Number(55); // abc inherits from Object via the Number class
abc.prop = 1; // so this is valid
console.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).
console.log. Try it in the browser console. Since abc now is an instance of Number and thus an instance of Object, SO's console get confused and log it as an object instead of a number.
console.log(abc);of first snippet showing only function, notpropproperty? How can I get function object's property?