简体   繁体   中英

strange behaviour in function and dictionary in nodejs

I am a beginner with node.js and I am trying the below code.

abc = function add( x, y) {
    return x + y
}
abc.A = "I am a string"
abc.B = 29
console.log( "abc is \n", abc, "\n and typeof ABC is ", typeof abc)
console.log( "abc.A is '"+ abc['A'] + "' and abc.B is", abc['B'] )

The output of this code is

abc is 
 function add( x, y) {
        return x + y
    } 
 and typeof ABC is function
abc.A is 'I am a string' and abc.B is 29

However if I define abc as a number in the beginning

abc = 459   
abc.A = "I am a string"
console.log( abc['A'] )

Then the output is

undefined

Can someone please explain why the first code works fine, but the second one doesn't?

everything in JS is a data type, oh yes JS has data types, contrary to popular beliefs, and one of those data types is function, which is a type of object, objects in JS can be created and modified dynamically allowing you to add, rename and delete properties unless otherwise specified. that is why you can dynamically add properties and you can even reassign the prototype on runtime. that is the reason why you can do that and not get an error and why you can use some of the other properties like, length or name, bc functions are just another object. toString method of the function just happens to print the implementation.

As per the 2nd part of your q you can not assign new properties to literal values but you can do var a = new Number(100) and then do a.prop='whatever' and will still be accessible.

In JavaScript, functions are objects, so you can add properties to them, just like if you created:

var abc = {};
abc.A = 'Whatever';

Numbers, strings, booleans are primitives and cannot have properties added to them. That's why you can't assign a property to a number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM