简体   繁体   English

nodejs中函数和字典中的异常行为

[英]strange behaviour in function and dictionary in nodejs

I am a beginner with node.js and I am trying the below code. 我是node.js的初学者,正在尝试以下代码。

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为数字

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. JS中的所有内容都是数据类型,哦,是的,与流行的看法相反,JS具有数据类型,而其中一种数据类型是函数,这是一种对象类型,可以动态创建和修改JS中的对象,允许您添加,除非另有说明,否则重命名和删除属性。 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. 这就是为什么您可以执行此操作而不会出错的原因,以及为什么可以使用其他一些属性(例如,length或name),bc函数只是另一个对象的原因。 toString method of the function just happens to print the implementation. 该函数的toString方法只是打印实现。

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. 根据q的第二部分,您不能将新属性分配给文字值,但可以执行var a = new Number(100) ,然后执行a.prop='whatever'并且仍然可以访问。

In JavaScript, functions are objects, so you can add properties to them, just like if you created: 在JavaScript中,函数是对象,因此可以向其添加属性,就像创建对象一样:

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. 这就是为什么您不能将属性分配给数字的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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